2015-06-02 69 views
2

爲什麼下面的代碼會輸出1?Javascript調用方法

function func(){ 
 
    alert(this) 
 
} 
 
var i = 1; 
 
func.call(i);

+1

'MDN'是你的朋友:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call – Adam

回答

2

定義

function.prototype.call(this,arg1,arg2,...);

因此,當您撥打func.call時,您傳遞的第一個參數將綁定到this變量。因此,在函數func中,任何this變量將被您的第一個參數替換爲1

要發揮進一步

可以擴展多個參數func,並進一步論證打電話,看看發生什麼事:

function func(a,b){ 
    alert(this + a*b); 
} 

func.call(1,2,3); 

召回的定義,第一個參數或func.callthis變量func。所以,你最終會運行

alert(1 + 2*3); 

**號:** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

**甚至進一步閱讀**

function.prototype.call還有一個親兄妹是function.prototype.apply。這兩個函數的第一個參數是指this變量。唯一的區別是function.prototype.apply接受數組中這樣的函數的參數。

所以不是

func.call(1,2,3); 

您將

func.apply(1,[2,3]); 

有它的樂趣玩電話了!

1

由於call的第一個參數是函數this值,語法是

function.call(thisArg[, arg1[, arg2[, ...]]]) 

作爲MDN

含義無論是作爲第一傳遞注意到參數call將爲this調用的函數

function func(){ 
    alert(this) 
} 

func.call("test"); // alerts "test" 

要傳遞的參數裏面,你傳遞一個this值,然後自變量的其餘部分將沿着該功能

function func(arg1, arg2, arg3){ 
    alert(this); // alerts "this_value" 
    alert(arg2); // alerts "kitty" 
} 

func.call("this_value", "hello", "kitty", "cat"); 

apply傳遞的參數的工作方式相同,但取而代之的是一系列參數

func.apply("this_value", ["hello", "kitty", "cat"]);