call
Function.prototype.myCall = function(context, ...args) {
// 判断是否是undefined和null
if (typeof context === 'undefined' || context === null) {
context = window
}
let fnSymbol = Symbol()
context[fnSymbol] = this
let fn = context[fnSymbol] (...args)
delete context[fnSymbol]
return fn
}
1,为传入的context扩展一个属性,将原函数指向这个属性
2,将context之外的所有参数全部传递给这个新属性,并将运行结果返回。
apply
Function.prototype.myApply = function(context, args) {
// 判断是否是undefined和null
if (typeof context === 'undefined' || context === null) {
context = window
}
let fnSymbol = Symbol()
context[fnSymbol] = this
let fn = context[fnSymbol] (...args)
return fn
}
思路和call是一样的只是传参不同方式而已
bind
Function.prototype.myBind = function(context) {
// 判断是否是undefined和null
if (typeof context === "undefined" || context === null) {
context = window;
}
self = this;
return function(...args) {
return self.apply(context, args);
}
}