call、apply、bind 都可以改变函数的this指向
- call 接受多个参数,第一个参数代替执行的this,后面的都是函数传入的参数----会立即执行函数
Function.prototype.wcall = function(content = window){
content.fn = this
let rest = [...arguments].slice(1)
let result = comntent.fn(rest)
delete content.fn
return result
}
- apply 接受两个参数,第一个参数代替执行的this,第二个参数是一个数组----会立即执行函数
Function.prototype.wapply = function(content = window){
content.fn = this
let rest = arguments[1] || []
let result = content.fn(...rest)
delete context.fn
return result
}
- bind接受多个参数,第一个参数代替执行的this,后面的参数是返回函数的接受参数----返回一个函数(且返回函数的原型上会有原函数的属性和方法)
Function.prototype.bind2 = function(content) {
if(typeof this != "function") {
throw Error("not a function")
}
let fn = this;
let args = [...arguments].slice(1);
let resFn = function() {
return fn.apply(this instanceof resFn ? this : content,args.concat(...arguments))
}
function mid() {}
mid.prototype = this.prototype
resFn.prototype = new mid()
return resFn
}