Closure issues and method defined elsewhere
I am new to Javascript so I cannot use the exact terminology.
Suppose I am defining 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 that myOtherObject.someMethod () works without using eval () as above?
+2
source to share
1 answer
someValue is local to someOtherMethod and cannot 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();
+1
source to share