实现apply、call、bind

实现原理:当意图把一个函数的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的区别就是传的参数形式不一样。call是一个一个的传,apply可以将参数以数组的形式传进去。...
    会飞小超人阅读 5,432评论 1 4
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,842评论 2 17
  • this 的指向 在 ES5 中,其实 this 的指向,始终坚持一个原理:this 永远指向最后调用它的那个对象...
    fenerchen阅读 596评论 0 9
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,712评论 1 45
  • 你这么多年的管理下来我觉得管理一点是管人管人一定是管心,你的时候千万不要参叉人情,今天是十月份然后呢工作有所分配然...
    有心人123阅读 209评论 0 0