views:

28

answers:

1

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 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()+")");

   }
}

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

+1  A: 

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