【发布时间】: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