美文网首页
实现apply、call、bind

实现apply、call、bind

作者: Ivy_study | 来源:发表于2019-02-28 15:13 被阅读0次

实现原理:当意图把一个函数的this值指向某个对象时,利用对象的属性值就可以达到目的。因为this的指向是在运行时确定的,obj.fn()的this指向obj.

Function.prototype.myCall = function(context, ...args) {
    const obj = context || window; // 当context为null时,this指向window
    obj.fn = this;  
    return obj.fn(...args); 
    delete obj.fn;
}
Function.prototype.myApply = function(context, args) {
    const obj = context || window;
    obj.fn = this;   

    return obj.fn(...args);
    delete obj.fn;
}
Function.prototype.myBind = function(context, ...args1) {
    const obj = context || window;
    obj.fn = this;

    return function(...args2) {
        obj.fn(...args1.concat(args2))
    }

    delete obj.fn;
}
Function.prototype.myBind2 = function(ctx, ...args1) {
    ctx = ctx || window;
    const _this = this;
    return function(...args2) {
        _this.apply(ctx, [...args1, ...args2]);
    }
}
function bar(verb, nounce) {
    console.log(`${this.user}${verb}${nounce}`);
    return {
        user: this.user
    }
}

const target = {
    user: 'i'
}

bar.myCall(target, 'am', 'ivy');
bar.myApply(target, ['am', 'ivy']);
const foo = bar.myBind2(target, 'am');
foo('ivy');

相关文章

网友评论

      本文标题:实现apply、call、bind

      本文链接:https://www.haomeiwen.com/subject/gbexuqtx.html