apply 和 call 和 bind 的区别,三个方法都是改变this 指向问题,bind 最大区别是返回一个新的函数,
apply 和 call 对于参数传入的区别:
①:函数.call(对象,arg1,arg2…)
②:函数.apply(对象,[arg1,arg2,…])
// step1: 把函数挂在到目标对象上
// step2: 执行函数
// step3: 删除step1中挂到目标对象上的函数,把目标对象”完璧归赵”
Function.prototype.myCall = function (context,...args) {
// content 是传入的上下文
const ctx = context || window
// 这里的this是值调用方法,把这个方法赋值给传入contenx上下文,然后再执行这个方法
ctx.func = this
ctx.func(...args)
//最后再这里删除该方法,否则对象的属性或者方法会越来越多
delete ctx.func
}
// apply 只是对于参数传入的不同
Function.prototype.myApply = function (context,...arr) {
const ctx = context || window
ctx.func = this
if(!arr) {
ctx.func()
}else{
ctx.func(...arr)
}
delete ctx.func
}
// bind 多加一步,返回一个新的函数
Function.prototype.myBind = function (context,...args) {
const ctx = context || window
ctx.func = this
return function(){
ctx.func(...args)
delete context.func
}
}
``