call | apply | bind | |
用法 | function.call(thisArg,arg1,arg2,arg3...) | ||
功能 | 使用一个指定的this值和单独给出的一个或者多个参数来调用一个函数。 | 创建一个新的函数, 当被调用时,将其this关键字设置为提供的值,在调用新函数时,在任何提供之前提供一个给定的参数序列 | |
返回值 | 使用调用者提供的this值和参数调用该函数的返回值,若方法无返回值,返回undefined。 | ||
注意点 | 1.this可以传null或者undefined,此时this指向window; 2.this参数可以传基本数据类型,原生call会自动用Object()转换; 3.函数是可以有返回值的; 4.将函数添加到指定对象中,用delete删除(消除副作用) | 整体与call类似,apply调用的时候,第二个参数是个数组 | |
步骤 | 1.获取第一个参数,构建对象 2.将对应函数传入该对象 3.获取参数并执行相应函数 4.删除该对象中的函数,消除副作用 5返回结果 | 1、将函数设置为对象的属性; 2、处理传入的参数; 3、返回函数的定义/引用; 4、外层执行接收的函数; 5、删除对象上第一步设置的函数; |
1.call函数
Function.prototype.myCall = function(){
let target = arguments[0]|| window || global
target.fn = this
let args = Array.from(arguments).slice(1)
let result = target.fn(...args)
delete target.fn
return result
}
2.apply函数
Function.prototype.myApply = function(){
let target = arguments[0]|| window || global
target.fn = this
let args = Array.from(arguments)[1]
let result = target.fn(...args)
delete target.fn
return result
}
3.bind函数
Function.prototype.myBind = function(context) {
const _this = this
const args = [...arguments].slice(1)
console.log(this)
// 返回一个函数
return function F() {
// 因为返回了一个函数,我们可以 new F(),所以需要判断
if (this instanceof F) {
// 忽略传入的this
return new _this(...args, ...arguments)
}
// 直接调用,将两边的参数拼接起来
return _this.apply(context, args.concat(...arguments))
}
}