It's easy to do without using eval
at all:
function getValue(path) {
var target = this;
path.split('.').forEach(function (branch) {
if (typeof target === "undefined") return;
target = (typeof target[branch] === "undefined") ? undefined : target[branch];
});
return target;
}
If you want to get properties starting from window
you can just call getValue("path.to.property")
. If you want to start from some other root object, use getValue.call(rootObject, "path.to.property")
.
The function could also be adapted to take the root object as an optional first parameter, but the idea remains the same.
See it in action.
Important: This will not work on Internet Explorer < 9 because Array.prototype.forEach
will not exist. You can fix that with
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisPointer */) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var thisPointer = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
fun.call(thisPointer, this[i], i, this);
}
}
};
}
eval
is strongly discouraged. – Daniel A. White Sep 19 '12 at 12:05eval
, I think you meant to useeval(b)
– Alexander Sep 19 '12 at 12:07[js] eval evil
on SO if you want to know more. – 11684 Sep 19 '12 at 12:08