2009-10-23 75 views
2

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

    } 
} 

是否有可能有 myOtherObject.someMethod()工作,而無需使用的eval()如上

回答

1

someValue是someOtherMethod本地的,無法以任何方式被myObj.someMethod()訪問。有兩種解決辦法:

一個)通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();