call

function Person(name, price) {
    this.name = name;
    this.price = price;
    this.msg = function() {
        console.log('我叫' + this.name)
    }
}
Function.prototype.myCall = function (thisArg = globalThis, ...arg) {
    const key = Symbol()
    thisArg[key] = this
    console.log(this)
    thisArg[key](...arg)
    delete thisArg[key]
    console.log(thisArg)
    return thisArg
}
let arg = {
    sex: 'nan',
    age: 20
}
console.log(Person.myCall(arg, 'test', '1000'))

apply

// 向原型添加一个方法 使所有的函数都可以用此方法
// thisArg(需要被添加属性或方法的对象)...arg(接受的参数)
Function.prototype.myApply = function (thisArg, arg) {
    // 如果thisArg不是很法值就返回对应环境的全局 如Window 
    if (!thisArg) {
        thisArg = globalThis
    }
    arg= arg? arg: []
    //添加一个独一无二的值 以免thisArg里面有一样名字的属性会被覆盖掉
    const key = Symbol()
    //这个this指向他的调用者this为asg 调用myCall的函数里面的this会变成thisArg
    thisArg[key] = this
    // 将函数里面的形参赋值
    thisArg[key](...arg)
    // 删除多余都属性
    delete thisArg[key]
    //apply的返回值是undefined
    return thisArg
}

console.log(Person.myApply(arg, ['祁纤', '10000']))

你可能感兴趣的:(call)