2013-02-16 99 views
-3

JavaScript函數是否附加到他們定義的任何特定對象或全局對象本身,我問這個問題,因爲你幾乎可以在任何對象上使用函數,天氣函數是否是該對象的一部分,我的意思是你可以指定函數引用你想要的任何對象,這意味着函數本身存儲在其他地方,然後我們將它們分配給任何其他對象方法。我對JavaScript函數感到困惑嗎?

請改正我我是JavaScript新手,但我對JavaScript有一定了解。

我知道使用這個關鍵字是用來引用當前的上下文代碼。

+0

我知道這個功能取決於它的調用方式 – user2019110 2013-02-16 06:06:38

+4

當發佈到堆棧溢出時,請發佈更好的標題。 – 2013-02-16 06:06:47

+1

我們無法給出答案,因爲我們看不到任何您參考的代碼。請提供代碼。 – 2013-02-16 06:07:18

回答

2

函數沒有附加到任何東西,但執行時,它們在this綁定到某個對象(除了ES5嚴格模式,其中this有時可能未定義)的上下文中這樣做。

哪個對象this指是的函數是如何調用的產品,如果它是爲一個對象中的一員,或如callapply是否一個功能被使用。

var obj = { 
    x: 20, 
    fn: function() { 
    console.log(this.x); 
    } 
}; 
obj.fn(); // prints 20 as `this` will now point to the object `obj` 

var x = 10; 
var fn = obj.fn; 
fn(); // prints 10 as `this` will now point to the global context, since we're invoking the function directly 

var newObj = { 
    x: 30 
}; 
fn.call(newObj); // prints 30 as `this` points to newObj 
fn.apply(newObj); // same as the above, but takes an the functions arguments as an array instead of individual arguments 
+0

非常感謝你,kinsey你救了我的靈魂。 – user2019110 2013-02-16 07:23:38