CatsAndMice / blog

📖 凌览的博客
http://www.linglan01.cn
79 stars 6 forks source link

JS 中如何实现 call/apply #22

Closed CatsAndMice closed 2 years ago

CatsAndMice commented 3 years ago

call/apply唯一区别: 传参类型不同


Function.prototype.myCall = function (self, params) {
    let isNull = self === null;
    let isUndefind = self === undefined
    let name = this.name;
    let type = typeof self
    if (isNull || isUndefind) {
        self = globalThis;
    }

    if (type === "string") {
        self = new String(self)
    }

    if (type === "number") {
        self = new Number(self)
    }
    self[name] = this;
    params ? self[name](params) : self[name](params);
}

Function.prototype.myApply = function (self, params) {
    let isNull = self === null;
    let isUndefind = self === undefined
    let name = this.name;
    let type = typeof self
    if (isNull || isUndefind) {
        self = globalThis;
    }

    if (type === "string") {
        self = new String(self)
    }

    if (type === "number") {
        self = new Number(self)
    }
    self[name] = this;
    params ? self[name](...params) : self[name]();
}

function fn() {
    console.log(name, this.name);
}

function fn1(params1, params2) {
    console.log(params1, params2, this);
}

let obj = {
    name: 'myCall'
}

let name = 'name'
fn.myCall(null)
fn1.myApply(null,[1,2])