美文网首页
call apply bind

call apply bind

作者: bestCindy | 来源:发表于2020-10-20 20:57 被阅读0次

call

Function.prototype.call = function (context = window, ...args) {
    if (typeof this != "function") {
        throw new TypeError("Type Error");
    };

    // 避免在把函数赋值给 context 对象的时候,因为属性名冲突而覆盖掉原有属性
    const fn = Symbol("fn");
    context[fn] = this;

    const res = context[fn](...args);
    delete context[fn];

    return res;
}

let obj = {
    name: "Cindy"
};
function fn(age, hobby) {
    console.log("name:" + this.name + "  " + "age:" + age + "  " + "hobby:" + hobby);
};

fn.call(obj, "18", "painting");

apply

Function.prototype.call = function (context = window, args) {
    if (typeof this != "function") {
        throw new TypeError("Type Error");
    };

    // 避免在把函数赋值给 context 对象的时候,因为属性名冲突而覆盖掉原有属性
    const fn = Symbol("fn");
    context[fn] = this;

    const res = context[fn](...args);
    delete context[fn];

    return res;
}

let obj = {
    name: "Cindy"
};
function fn(age, hobby) {
    console.log("name:" + this.name + "  " + "age:" + age + "  " + "hobby:" + hobby);
};

fn.call(obj, ["18", "painting"]);

bind

Function.prototype.bind = function(context, ...args) {
    if (typeof this !== "function") {
        throw new Error("Type Error");
    };

    //保存 this 的值
    var self = this;

    return function F() {
        return self.apply(context, [...args, ...arguments]);
    }
}

let obj = {
    name: "Cindy"
};
function fn(age, hobby) {
    console.log("name:" + this.name + "  " + "age:" + age + "  " + "hobby:" + hobby);
};

newFn = fn.bind(obj, "18", "painting");

newFn();

相关文章

网友评论

      本文标题:call apply bind

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