【问题标题】:Issues with closure and a method defined elsewhere闭包问题和其他地方定义的方法
【发布时间】:2009-10-23 20:58:48
【问题描述】:

我是 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() 工作?

【问题讨论】:

    标签: javascript methods closures


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多