apply
function myApply(obj,args){
/*
1. this指向调用者
2. 使用隐式绑定 obj.fn = this
3. obj.fn()
4. 调用完以后删除fn
*/
// 确保obj是一个对象
obj = (obj===null || obj === undefined) ? window:Object(obj)
obj.fn = this
obj.fn(...args)
delete obj.fn
}
// 添加到Function原型上
Function.prototype.myApply = myApply
call
Function.prototype.myCall = function(obj,...args){
obj = (obj===null || obj === undefined) ? window:Object(obj)
obj.fn = this
obj.fn(...args)
delete obj.fn
}
bind
Function.prototype.myBind = function(obj,...args){
// 判断是否为对象类型
obj = obj ===null||obj ===undefined ? window:Object(obj)
obj.fn = this
return (...fnArgs)=>{
obj.fn(...args,...fnArgs)
}
}
new
function myNew(fn){
/*
0. 判断是否是一个函数
1. 创建一个空对象,对象的原型指向fn的原型
2. fn绑定this
3. 返回对象或fn的返回值
*/
if (typeof fn !== 'function') {
throw 'must be a function'
}
var obj = Object.create(fn.prototype)
var args = [...arguments].slice(1)
var result = fn.apply(obj,args)
if ((typeof result ==='object' && typeof result !== null) || typeof result ==='function') {
return result
}
return obj
}
标签:function,...,obj,args,JS,result,手写,fn
From: https://www.cnblogs.com/hyf120/p/17023847.html