2015-06-02 70 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"]);