简体   繁体   English

仅从对象名称中获取对Javascript对象的引用?

[英]Get reference to a Javascript Object from the Object name alone?

In javascript, Suppose I have a string called, str = "document" . 在javascript中,假设我有一个名为str = "document"的字符串。 How do I get the Object, Document which references it from the string name? 如何获得从字符串名称引用它的对象,文档?

So what I would like to have is, take the string and get the reference to the Object, with the string name in the current closure. 所以我想拥有的是,使用字符串并获取对Object的引用,并在当前闭包中使用字符串名称。

str = "window"; I would need the reference to the Window Object here. 我在这里需要引用Window对象。

Is there a dynamic way to get these references? 有没有动态的方式来获取这些参考?

function getObject(str){
/* logic */

} 

getObject('window'); // returns [object Window]
getObject('document'); // returns [object HTMLDocument]

Use Case: I'm trying to fuzz a few stuff which comes from an array of strings. 用例:我正在尝试模糊一些来自字符串数组的东西。 Here is what am trying to do. 这是尝试做的事情。 Would be great if you guys could tell me the best way to do this. 如果你们能告诉我最好的方法,那将很棒。

function hook(Obj, prop, newValue) {
    console.log(Obj, typeof Obj, prop);
        Object.defineProperty(Obj, prop, {
            'get': function () {
                return newValue;
            }
        });     
}

function test(Obj, prop) {
    var before = Obj[prop];
    hook(Obj, prop, 'xyz);
    var after = Obj[prop];

    if( before == after){
        alert(Obj + '.
        '+ prop +'
        Not Changed ');
    } else {
        alert(Obj + '.
        '+ prop +'
        Changed ');
    }
}

var data = [['document', 'domain'], ['window.document', 'location'], ['location', 'href']];
var i=0;
for(i=0; i<data.length; i++){
    test(data[i][0], data[i][1]);
}

If your object is a global one, then you can do it like this - 如果您的对象是全局对象,则可以这样操作-

window['your-window-object'];

If it a property of another object, then you can do it like this - 如果它是另一个对象的属性,则可以这样操作-

obj['property-name'];

In every cases, you need to know the scope of the variable. 在每种情况下,您都需要了解变量的范围。

Example - 范例-

var doc = window['document'];  // gives you the document object
var obj = {
    prop1: 1;
    prop2: 2
}

var propValue = obj['prop1']; // gives you 1

For local variables, you might be tempted to use eval , but you should almost always it. 对于局部变量,您可能会想使用eval ,但几乎应该始终使用它。 For more information, just google it. 有关更多信息,只需将其谷歌搜索即可

You can obtain the reference by using 您可以通过使用获得参考

function getObject(str)
{
    console.log(this[str]);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM