在 Function 对象中包含 apply 与 call 这两种方法,通过它们调用的函数的 this 引用,可以指向任意特定的对象。也就是说,可以理解为它们能够显式地指定接收方对象。
下面是一个使用了 apply 方法与 call 方法的例子。
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| function hzhF() { |
| console.log(this.x); |
| } |
| var hzh = { x: 4 }; |
| |
| console.log("通过apply调用函数hzhF:"); |
| hzhF.apply(hzh); |
| console.log(""); |
| console.log("直接调用函数hzhF:"); |
| hzhF(hzh); |
| console.log(""); |
| console.log("通过call调用函数hzhF:"); |
| hzhF.call(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); |
| 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]); |
| console.log(""); |
| console.log("直接调用函数hzh:"); |
| hzh( {x:4}, [1,2] ); |
| console.log(""); |
| console.log("通过call方法调用函数hzh:"); |
| hzh.call( { x:4 }, 1, 2 ); |
| 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 调用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?