我注意到一些東西在玩耍時引發了一個快速問題。Javascript:全局上下文和函數上下文聲明
當在全局/窗口上下文中執行代碼時,將任何函數聲明作爲方法添加到窗口對象中。
但是,當我在另一個對象的上下文中,編寫一個函數聲明不會將該方法添加到我的對象方法。
function functionInGlobalCtx() { // This will be added as a function to the window object
// code...
}
var myObject = {};
myObject.myObjectFunction = function() {
var $this = this; // The context here is the 'myObject' object
function functionHopefullyInMyObjectCtx() {
// code...
}
}
myObject.myObjectFunction();
爲什麼函數聲明作爲窗口對象的一部分而不是對象的一部分存在?
這是簡單的'如何JavaScript的作品'(特殊規則適用於全球上下文嗎?)還是我錯過了什麼?
謝謝。