开发者

Issues with closure and a method defined elsewhere

开发者 https://www.devze.com 2022-12-09 13:31 出处:网络
I am pretty new at Javascript so I may not be using the exact terminology. Suppose that I define an object literal as such.

I am pretty new at Javascript so I may not be using the exact terminology.

Suppose that I define an object literal as such.

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

And then we assign the function to another object like this.

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

      //If we did this, then the function would have access t开发者_开发问答o "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()+")");

   }
}

Is it possible to have myOtherObject.someMethod() work without using eval() as above?


someValue is local to someOtherMethod and can not be accessed by myObj.someMethod() in any way. There are two solutions:

a) Pass someValue as a parameter to the first method:

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) Store someValue as a member of the object itself, not as a local variable:

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消