js手写apply、call、new、bind方法

call

Function.prototype.mCall = function (_this,...args){
    if (!_this) _this = Object.create(null)
    _this.fn = this
    let res = _this.fn(...args)
    delete _this.fn
    return res
}

apply

Function.prototype.mApplay = function (_this,args=[]){
    if (!Array.isArray(args)){
        return TypeError('参数必须是数组')
    }
    if (!_this) _this = Object.create(null)
    _this.fn = this
    let res = _this.fn(...args)
    delete _this.fn
    return res
}

new

Function.prototype.mNew = function(fn,...args){
    const instance = Object.create(fn.prototype)
    const res = fn.apply(instance,args)
    return typeof res === "object" ? res : instance;
}

bind

Function.prototype.mBind= function (_this,...args){
    const fn = this
    return function F(...args2){
        return this instanceof F ? fn(...args,...args2) :fn.apply(_this,args.concat(args2))
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容