- 1、call()方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数(即、可以改变当前函数的this指向,还会让当前函数执行)
Function.prototype.myCall = function(context){
if(typeof this !== 'function'){
console.error("type error");
}
let args = [...arguments].slice(1)
let result = null
context = (context === null || context === undefined)? window:context
context.fn = this
context.fn(...args)
delete context.fn
return result
}
- 2、apply(),该方法与call()基本相同
- 实现如下:
Function.prototype.myApply = function(context){
if(typeof this !== 'function'){
console.error("type error");
}
context = (context === null || context === undefined)? window:context
context.fn = this
let result = arguments[1]? context.fn(...arguments[1]):context.fn()
delete context.fn
return result
}
- 3、bind()会返回一个新的函数,不会自动执行。这个函数的this值被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用时使用
Function.prototype.myBind = function(context){
if(typeof this !== 'function'){
console.error("type error");
}
let args = [...arguments].slice(1)
let ts = this
return function Fn(){
return ts.apply(
this instanceof Fn ? this : context,
args.concat(...arguments)
)
}
}