Function.prototype.mybind = function(context = window,...args){
const fn = this;
let bindFn = function(...newArgs){
return fn.apply(this instanceof bindFn ? this : context,args.concat(newArgs))
}
if(this.prototype){
bindFn.prototype = Object.create(this.prototype)
}
return bindFn
}
Function.prototype.myBind = function(context = window, ...args) {
// 保存原始函数
const self = this;
// 返回一个新函数
return function joker(...newArgs) {
// 判断是否为构造函数调用
if(this instanceof joker){
console.log(999)
let empty = function(){}
empty.prototype = Object.assign(self.prototype,context)
let j = new empty()
self.apply(j,args.concat(newArgs))
return j
}else{
console.log(888)
return self.apply(context, args.concat(newArgs));
}
};
};
function test(){
console.log('Outer bind text:',this.name)
}
const o = {
name:'Just a mybind Demo'
}
const j = test.myBind(o)
const nj = new j()
console