黄子涵

5.15 apply 与 call

在 Function 对象中包含 apply 与 call 这两种方法,通过它们调用的函数的 this 引用,可以指向任意特定的对象。也就是说,可以理解为它们能够显式地指定接收方对象。

下面是一个使用了 apply 方法与 call 方法的例子。

// function hzh(a, b) {
//        console.log("this.x = " + this.x ,", a = " + a + ", b = " + b);
// }

// console.log("通过apply方法");
// hzh.apply( { x:4 }, [1, 2]); // 作为第2个参数的数列中的元素都是函数hzh的参数
// hzh( {x:4}, [1,2] );

// hzh.call( { x:4 }, 1, 2 );

function hzhF() {
       console.log(this.x);
}
var hzh = { x: 4 };

console.log("通过apply调用函数hzhF:");
hzhF.apply(hzh); // 通过 apply 调用函数 hzhF。函数内的 this 引用引用了对象 hzh。
console.log("");
console.log("直接调用函数hzhF:");
hzhF(hzh);
console.log("");
console.log("通过call调用函数hzhF:");
hzhF.call(hzh);  // 通过 call 调用函数 hzhF。函数内的 this 引用引用了对象 hzh。
console.log("");
console.log("通过调用函数hzhF:");
hzhF(hzh);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
通过apply调用函数hzhF:
4

直接调用函数hzhF:
undefined

通过call调用函数hzhF:
4

通过调用函数hzhF:
undefined

[Done] exited with code=0 in 0.189 seconds
// 将接收方对象指定为另一个对象并进行方法调用
var hzh = {
       x:3,
       huangzihan: function () {
              console.log("方法已经被调用!" + this.x);
       }
}

var hzh2 = { x:4 };
console.log("通过apply调用hzh.huangzihan方法:");
hzh.huangzihan.apply(hzh2); // 通过apply调用hzh.huangzihan方法。方法内的this引用引用了对象
console.log("");
console.log("直接调用hzh.huangzihan方法:");
hzh.huangzihan(hzh2);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
通过apply调用hzh.huangzihan方法:
方法已经被调用!4

直接调用hzh.huangzihan方法:
方法已经被调用!3

[Done] exited with code=0 in 0.184 seconds

对 Function 对象 f 使用 apply 或 call 方法,就能够调用该函数。不考虑函数内的 this 引用的话,这和 f() 的用法是一样的。两者的区别在于被调用的函数(方法)内的 this 引用,this 引用的是作为 apply/call 的第一个参数被传递的对象。而 apply 与 call 之间的不同之处在于两者对其他参数的传递方式。对于 apply 来说,剩余的参数将通过数组来传递,而 call 是直接按原样传递形参。请通过下面具体的例子来了解这一差异。

function hzh(a, b) {
       console.log("this.x = " + this.x ,", a = " + a + ", b = " + b);
}

console.log("通过apply方法调用函数hzh:");
hzh.apply( { x:4 }, [1, 2]); // 作为第2个参数的数列中的元素都是函数hzh的参数
console.log("");
console.log("直接调用函数hzh:");
hzh( {x:4}, [1,2] );
console.log("");
console.log("通过call方法调用函数hzh:");
hzh.call( { x:4 }, 1, 2 );   // 从第2个参数起的参数都是函数hzh的参数
console.log("");
console.log("直接调用函数hzh:");
hzh( {x:4}, 1, 2 );
[Running] node "e:\HMV\JavaScript\JavaScript.js"
通过apply方法调用函数hzh:
this.x = 4 , a = 1, b = 2

直接调用函数hzh:
this.x = undefined , a = [object Object], b = 1,2

通过call方法调用函数hzh:
this.x = 4 , a = 1, b = 2

直接调用函数hzh:
this.x = undefined , a = [object Object], b = 1

[Done] exited with code=0 in 0.183 seconds

在实际的编程过程中,我们常常会为了函数回调而使用 apply 或 call 调用。

posted @ 2022-05-28 16:33  黄子涵  阅读(21)  评论(0编辑  收藏  举报