js call()和apply()

本文介绍 JavaScript 中 call() 和 apply() 方法的作用,通过示例展示了如何利用这两种方法来改变函数内部 this 的指向。

Both call() and apply() are methods we can use to assign the this pointer for the duration of a method invocation. As an example, here is how we could use the call() method:


var x = 10;

var o = { x: 15 };

 

function f()

{

    alert(this.x);

}

 

f();

f.call(o);



The first invocation of f() will display the value of 10, because this references the global object. The second invocation (via the call method) however, will display the value 15. 15 is the value of the x property inside object o. The call() method invokes the function and uses its first parameter as the this pointer inside the body of the function. In other words - we've told the runtime what object to reference as this while executing inside of function f().




var x = 10;

var o = { x: 15 };

function f(message)

{

    alert(message);

    alert(this.x);

}

 

f("invoking f");

f.call(o, "invoking f via call");



The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.



var x = 10;

var o = { x: 15 };

function f(message)

{

    alert(message);

    alert(this.x);

}

 

f("invoking f");

f.apply(o, ["invoking f through apply"]);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值