关闭问题和其他地方定义的方法

时间:2009-10-23 20:58:48

标签: javascript methods closures

我是Javascript的新手,所以我可能没有使用确切的术语。

假设我定义了一个对象文字。

var myObj = { 
   someMethod:function() {
      //can we have access to "someValue" via closure?
      alert(someValue);
   }
}

然后我们将函数分配给另一个这样的对象。

var myOtherObject  = {
   someOtherMethod:function() {
      var someValue = 'Hello World';

      //If we did this, then the function would have access to "someValue"
      this.aMethod = function() {
        alert(someValue);
      }

      //This does not work for "someMethod" to have access to "someValue"
      //this.someMethod = myObj.someMethod;

      //This does work, however I would like to avoid the use of eval()
      this.someMethod = eval("("+myObj.someMethod.toString()+")");

   }
}

是否可以在不使用 eval()的情况下使 myOtherObject.someMethod()工作?

1 个答案:

答案 0 :(得分:1)

someValue是someOtherMethod的本地,myObj.someMethod()无法以任何方式访问它。有两种解决方案:

a)将someValue作为参数传递给第一个方法:

var myObj = { 
   someMethod:function(someValue) {
      alert(someValue);
   }
}
var myOtherObject  = {
   someOtherMethod:function() {
      var someValue = 'Hello World';
      // The next line illustrates the 'closure' concept
      // since someValue will exist in this newly created function
      this.someMethod = function () { myObj.someMethod(someValue); };
   }
}
myOtherObject.someOtherMethod();
myOtherObject.someMethod();

b)将someValue存储为对象本身的成员,而不是局部变量:

var myObj = { 
   someMethod:function() {
      alert(this.someValue);
   }
}
var myOtherObject  = {
   someOtherMethod:function() {
      this.someValue = 'Hello World';
      this.someMethod = myObj.someMethod;
   }
}
myOtherObject.someOtherMethod();
// 'this' in someMethod will here refer to the new myOtherObject
myOtherObject.someMethod();