如何从名称作为字符串创建对象的引用?

时间:2011-06-10 10:10:37

标签: object javascript-events javascript-objects

window[objref]不起作用 self[objref]不起作用

这是jsfiddle

以下是代码:

var bob = {
    n: {},
    y: {
        somekey: 12,
        oo: 'yah',
        pop: {
            t: 36
        }
    },
    m: function() {},
    l: 'hi'
};


function membersOf(s) {

    //var o = window[s]; // returns false false
    // var o = self[s]; // returns false false
    var o = s; // returns ["0", "1", "2", "3", "4"] ["somekey", "oo", "pop"]

    var ret_array = [];
    for (var p in o) {
        if (o[p] != o.constructor.prototype[p]) {
            ret_array.push(p);
        }
    }
    if (ret_array.length === 0) {
        return false;
    } else {
        return ret_array;
    }
}

var ref = 'bob.y';
var byname = membersOf(ref);
var byval = membersOf(bob.y);
console.log(byname, byval);

1 个答案:

答案 0 :(得分:1)

您是否尝试过var byval = membersOf(eval(ref));