闭包和其他地方定义的方法的问题
我对 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() 工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
someValue 是 someOtherMethod 的本地变量,无法通过 myObj.someMethod() 以任何方式访问。有两种解决方案:
a) 将 someValue 作为参数传递给第一个方法:
b) 将 someValue 存储为对象本身的成员,而不是局部变量:
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:
b) Store someValue as a member of the object itself, not as a local variable: