2014-03-01 160 views
1

我使用anotherFunction函數基於來自對象someObjectsomeFunction定義了一個名爲anotherObject的對象。基於另一個對象的屬性定義對象的屬性

var someObject={ 
someFunction:function(){ 
    return this; 
} 
}; 

console.log(someObject.someFunction()===someObject);//true 

var someFunc=someObject.someFunction; 
console.log(someFunc===someObject.someFunction);//true 
//the function does not have the same context as that of the function called earlier... 
console.log(someFunc()===someObject);//false 

var anotherObject={ 
anotherFunction:someObject.someFunction 
}; 

console.log(anotherObject.anotherFunction===someObject.someFunction);//true 
console.log(anotherObject[anotherFunction]()===anotherObject);//true; 
console.log(anotherObject.anotherFunction()===someObject);//false 

Firefox Scratchpad報告未定義功能anotherFunction

+0

(函數(){})==(函數(){}) – bjb568

+0

'anotherObject [anotherFunction] ()'是垃圾 – Bergi

+0

你的問題到底是什麼? – Bergi

回答

0

就是這樣的JavaScript函數實際工作中,someFunction是一個函數,它的責任是在當前背景下返回this,不管是這一個:

var someFunc=someObject.someFunction; 

您可以使用叫它致電或與你喜歡的任何環境中應用:

var myobj = {}; 
console.log(someFunc.call(myobj)===myobj);//true 
console.log(someFunc.apply(myobj)===myobj);//true 

不管你通過什麼作爲第一個參數在callapply,你的函數會返回一個非常對象。所以當你看到你的函數做它應該做的事情,但是如果你希望它總是返回你的第一個對象someObject,你不需要使用this關鍵字。

閱讀my answerHow does JavaScript .prototype work?,我試圖在前兩部分中深入探討這個概念。

而且也這是你可以找到關於這個概念的最好的資源之一:

Understanding JavaScript Function Invocation and 「this」

+0

我想知道爲什麼函數'someObject.someFunction'沒有被複制到'anotherObject.anotherFunction'.I確實瞭解了一點關於調用和應用 – vamsiampolu

+1

@ user2309862:你是什麼意思'未被複制?當你像'anotherFunction:someObject.someFunction'一樣創建你的函數時,它只會創建對原始函數的引用。 –

+0

你是說,將一個屬性添加到已經傳遞給一個更高階函數的函數將會修改原始函數 – vamsiampolu

相關問題