gpt4 book ai didi

javascript - 闭包问题和别处定义的方法

转载 作者:行者123 更新时间:2023-11-30 06:08:57 25 4
gpt4 key购买 nike

我是 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() 工作?

最佳答案

someValue 是 someOtherMethod 的本地值,myObj.someMethod() 无法以任何方式访问。有两种解决方案:

a) 将 someValue 作为参数传递给第一个方法:

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) 将 someValue 存储为对象本身的成员,而不是局部变量:

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

关于javascript - 闭包问题和别处定义的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1615859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com