改变 this 指向、深入理解 call/apply/bind 的原理

72 阅读1分钟

call、apply 和 bind 是干嘛的?如何使用?它们之间有哪些区别?

call apply bind.jpg

call、apply 和 bind 之间的区别比较大,前两者在改变 this 指向的同时,也会把目标函数给执行掉;后者则只负责改造 this,不作任何执行操作。

Function.prototype.myCall = function(context, ...args) { 
    // step1: 把函数挂到目标对象上(这里的 this 就是我们要改造的的那个函数) 
    context.func = this // step2: 执行函数,利用扩展运算符将数组展开
    context.func(...args) // step3: 删除 step1 中挂到目标对象上的函数,把目标对象”完璧归赵” 
    delete context.func
}