call、apply、bind 运用 JS 简单实现
前言知识
作为一名合格的前端仔,至少要了解Javascript的基础知识;
了解 JavaScript 中 this 基础知识,因为本文会扩展你对 js 中 this 的认知;
回忆this
详细了解请点击 换种方式理解 JavaScript 中的 this
this
总是指向当前函数的所有者(调用者),它永远指向最后调用它的那个对象,这就是精髓。
① 当this
所在的函数被普通调用时,它指向 window (最外层) ,如果当前是严格模式,则指向 undefined;
② 当this
所在的函数被以 object.fn() 形式调用时,它指向 object;
③ 当this
的使用加入 call、apply 后,如下:
const b = { name: "onleap" } function a(x,y,z) { console.log(this.name); console.log(x,y,z); } a.call(b,5,2,0); //输出 onleap 和 5,2,0 function a(x,y,z) { console.log(this.name); console.log(x,y,z); } a.apply(b,[5,2,3]) //输出 onleap 和 5,2,3复制代码
④ 当this
的使用加入 bind 后,如下:
const b = { name: "xiaowu" } function a() { console.log(this.name); } a.bind(b, 5, 2, 3); //此时控制台没输出,因bind会重新生成并且返回一个函数,此函数的 this 指向第一个参数 // 将上面最后一行换成如下代码 const c = a.bind(b, 5, 2, 3); c(); //此时输出 xiaowu复制代码
自实现 call
:
在JS函数原型上定义自己的myCall
方法:
思路:
通过对象属性的方式调用函数,这个函数里面的
this
指向这个对象;每次调用新增一个 symbol 属性,调用完毕删除;
这个 symbol 属性就是调用
mycall
方法的函数;函数形参中使用
...arg
是将多个形参都塞到一个数组里,在函数内部使用arg这个变量时,就是包含所有形参的数组;在调用
context[fn](...arg)
时候,...arg
是为了展开数组,依次传入参数调用函数;
代码:
Function.prototype.myCall = function (context, ...arg) { const fn = Symbol('临时的属性'); context[fn] = this; context[fn](...arg); delete context[fn]; }复制代码
自实现 apply
:
在JS函数原型上定义自己的myApply
方法:
思路:
同 call 理,只是 apply 传递的第二个参数是数组,这里我们只需要在调用时,将参数用
...
把数组展开即可数组;
代码:
Function.prototype.myApply = function (context, arg) { const fn = Symbol('临时的属性'); context[fn] = this; context[fn](...arg); delete context[fn]; } const obj1 = { a: 1 } test.myApply(obj1, [2, 3, 4]);复制代码
自实现 bind
:
在JS函数原型上定义自己的myBind
方法:
思路:
bind 跟 apply,call 的本质区别, bind 不会改变原函数的
this
指向,只会返回一个新的函数(我们想要的那个this
指向),并且不会调用。但是 apply 和 bind 会改变原函数的this
指向并且直接调用;
代码:
Function.prototype.myBind = function (context, ...firstarg) { const that = this; const bindFn = function (...secoundarg) { return that.myCall(context, ...firstarg, ...secoundarg); } bindFn.prototype = Object.create(that.prototype); return bindFn; } var fnbind = test.myBind(obj, 2); fnbind(3);复制代码
总结:
call、apply、bind 都是函数对象的一个方法,它们的作用都是改变函数的调用对象; call 和 apply 都是改变上下文中的this
并立即执行这个函数,bind 方法可以让对应的函数想什么时候调就什么时候调用,并且可以将参数在执行的时候添加,这是它们的区别,根据自己的实际情况来选择使用;现在都 2022 年了,感觉大家基本不会使用这几个方法,但是我们一定要知道它们的原理!
感兴趣的可以自己去手动实现下,乐趣多多,让自己也懂得更多。
作者:江南宋鸭丝
链接:https://juejin.cn/post/7054467538876366855