Javascript:将字符串解释为对象引用? [英] Javascript: interpret string as object reference?

查看:127
本文介绍了Javascript:将字符串解释为对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript使用变量作为对象名称

如何做我让JS将字符串视为对先前定义的对象的引用?简化:

How do I get JS to treat a string as a reference to a previously defined object? Simplified:

var myObject = new MyObject();

var myString = "myObject";

var wantThisToWork = myString.myproperty;


推荐答案

如果变量在全局范围内,您可以将其作为全局对象的属性访问

If the variable is in the global scope, you can access it as a property of the global object

var a = "hello world";
var varName = "a";
console.log( window[varName] ); // outputs hello world
console.log( this[varName] ); // also works (this === window) in this case

但是,如果它是局部变量,唯一的方法是使用 eval 免责声明

However, if it's a local variable, the only way is to use eval (disclaimer)

function () {
  var a = "hello world";
  var varName = "a";
  console.log( this[varName] ); // won't work
  console.log( eval(varName) ); // Does work
}

除非你可以将动态变量放入一个对象并访问它就像一个属性

Unless you can put your dynamic variables into an object and access it like a property

function () {
  var scope = {
    a: "hello world";
  };
  var varName = "a";
  console.log( scope[varName] ); // works
}

这篇关于Javascript:将字符串解释为对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆