apply-call-bind

怎甘沉沦 提交于 2020-04-07 21:48:54

call:

var foo  ={
    value:1
}

function bar(name,age) {
    console.log(this.value);
    console.log(name);
    console.log(age);
}
//bar.call(foo,'gongtao',11);

Function.prototype.call2 = function (context) {
    var args = [];
    for (var i = 1, len = arguments.length; i < len; i++) {
        args.push(arguments[i]);
    }
    context.fn = this;
    context.fn(...args);
    delete context.fn;
}

bar.call2(foo,'gongtao',111);

 

apply:

var foo = {
    value: 1
}

function bar(name, age) {
    console.log(this.value);
    console.log(name);
    console.log(age);
}

//bar.apply(foo);

Function.prototype.apply2 = function (context, arr) {
    var context = context || window;
    if (!arr) {
        context.fn();
    } else {
        context.fn = this;
        context.fn(...arr);
    }

    delete context.fn;
}

bar.apply2(foo, ["gongtao", 11]);

 

Bind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!