如何在JavaScript中dynamic访问本地作用域?

如果要dynamic使用全局函数和variables,可以使用:

window[functionName](window[varName]); 

是否有可能做同样的事情在本地范围内的variables?

此代码正常工作,但目前使用eval,我试图想如何做到这一点。

 var test = function(){ //this = window var a, b, c; //private variables var prop = function(name, def){ //this = window eval(name+ ' = ' + (def.toSource() || undefined) + ';'); return function(value){ //this = test object if ( !value) { return eval('(' + name + ')'); } eval(name + ' = value;') return this; }; }; return { a:prop('a', 1), b:prop('b', 2), c:prop('c', 3), d:function(){ //to show that they are accessible via to methods return [a,b,c]; } }; }(); >>>test Object >>>test.prop undefined >>>test.a function() >>>test.a() 1 //returns the default >>>test.a(123) Object //returns the object >>>test.a() 123 //returns the changed private variable >>>test.d() [123,2,3] 

不,像crescentfresh说。 下面你可以find一个没有eval的例子,但是有一个内部的私有对象。

 var test = function () { var prv={ }; function prop(name, def) { prv[name] = def; return function(value) { // if (!value) is true for 'undefined', 'null', '0', NaN, '' (empty string) and false. // I assume you wanted undefined. If you also want null add: || value===null // Another way is to check arguments.length to get how many parameters was // given to this function when it was called. if (typeof value === "undefined"){ //check if hasOwnProperty so you don't unexpected results from //the objects prototype. return Object.prototype.hasOwnProperty.call(prv,name) ? prv[name] : undefined; } prv[name]=value; return this; } }; return pub = { a:prop('a', 1), b:prop('b', 2), c:prop('c', 3), d:function(){ //to show that they are accessible via two methods //This is a case where 'with' could be used since it only reads from the object. return [prv.a,prv.b,prv.c]; } }; }(); 

要回答你的问题,不,在没有使用eval()情况下,没有办法在本地范围内进行dynamicvariables查找。

最好的select是让你的“范围”只是一个常规的对象(即"{}" ),并将数据粘贴在那里。

希望我不会过于简化,但是如何使用对象这么简单?

 var test = { getValue : function(localName){ return this[localName]; }, setValue : function(localName, value){ return this[localName] = value; } }; >>> test.a = 123 >>> test.getValue('a') 123 >>> test.a 123 >>> test.setValue('b', 999) 999 >>> test.b 999