Function.prototype.myCall=function(context,...args){if(typeofthis!=='function'){thrownewError('type error')}
context = context || window
context.fn =thislet result = context.fn(...args)return result
}functionPerson(name, age){this.name = name
this.age = age
console.log('name=',this.name)
console.log('age=',this.age)
console.log('num=',this.num)}let obj ={num:100}
Person.myCall(obj,'lisi',18)
2. 手写apply函数
Function.prototype.myApply=function(context, args){if(typeofthis!=='function'){thrownewError('type error')}
context = context || window
context.fn =thislet result = context.fn(...args)delete context.fn
return result
}functionPerson(name, age){this.name = name
this.age = age
return`${this.name},${this.age},num=${this.num}`}let obj ={num:100}
console.log(Person.myApply(obj,['lisi',18]))
3. 手写bind函数
Function.prototype.myBind=function(context,...args1){if(typeofthis!=='function'){thrownewError('error')}const _this =thisreturnfunction(...args2){return_this.apply(context,[...args1,...args2])}}functiontest(name, age){this.name = name
this.age = age
returnthis.name +','+this.age +','+this.num
}let obj ={num:100}let res = test.myBind(obj,'lisi')
console.log(res(18))
4. 手写new操作符
functionmyNew(constructor,...args){let newObj ={}
newObj.__proto__ = constructor.prototype
let res =constructor.apply(newObj, args)return res instanceofObject? res : newObj
}functionPerson(name, age){this.name = name
this.age = age
}const person =myNew(Person,'lisi',18)
console.log(person)
console.log(person.__proto__ ===Person.prototype)
5. 手写instanceof方法
// 注意:instanceof只能用来判断复杂数据类型functionmyInstanceof(left, right){if(left ===null||typeof left !=='object'){thrownewError('type error')}let proto = left.__proto__
let prototype = right.prototype
while(true){if(!proto)returnfalseif(proto === prototype)returntrue
proto = proto.__proto__
}}let res1 =myInstanceof([1,2], Array)
console.log(res1)let res2 =myInstanceof({a:1}, Object)
console.log(res2)let res3 =myInstanceof(null, Function)
console.log(res3)