bind
-
mdn 解释:
返回:一个原函数的拷贝,并拥有指定的 this 值和初始参数。 -
自定义实现 返回一个函数
Function.prototype.myBind = function (context, ...args) {
// 解构传入参数成一个数组
return (...rest) => {
return this.call(context, ...args, ...rest) // 解构(展开数组)
}
}
function test (a, b, c) {
return a + b + c
}
test.bind(this)
let r = test.myBind(this, 1, 2) // 调用bind返回一个函数(可以传一部分参数)
console.log(r(3)) // 调用bind后的函数(可以传剩下的一部分参数)
apply
- mdn解释:
返回:使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。
Function.prototype.myApply = function (context, args) {
return this.call(context, ...args)
}
function test (a, b, c) {
return a + b + c
}
let r = test.myApply(this, [1, 2, 3])
console.log(r)
call
- mdn解释:
注意:该方法的语法和作用与 apply() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。
Function.prototype.myCall = function (context, ...args) {
return this.call(context, ...args)
}
function test (a, b, c) {
return a + b + c
}
let r = test.myCall(this, 1, 2, 3)
console.log(r)
- 总结:
- 调用bind,传入一个对象,将原函数拷贝一份并把函数里面用到的this指向传入的对象,返回拷贝后的函数。然后调用拷贝后的函数,传入必要的参数。
- 调用call,传入多个参数,第一个是对象,后面是一个参数列表,函数调用传入的参数,如果函数调用中用到this,则将this指向传入的对象,最后返回函数调用的返回值,如果函数没有返回值,则返回null
- 调用apply,传入两个参数,第一个是对象,第二个是一个数组,数组中包含函数调用时需要的参数,调用过程同call