JavaScript call, apply, bind 实现

102 阅读1分钟

实现Call:

Function.prototype.myCall = function (obj, ...args){
    let sym = Symbol();
    obj[sym] = this;
    let res = obj[sym](...args)
    delete obj[sym]
    return res
}

测试用例:

let person = {
    firstName: "Allen",
    lastName: "Wang"
}

let printName = function (city){
    console.log(this.firstName + " " + this.lastName + " " + city)
}

printName.call(person, "Beijing") // Allen Wang Beijing
printName.myCall(person, "Beijing") // Allen Wang Beijing

实现 Apply:

Function.prototype.myApply = function(obj, ...args) {
    let sym = Symbol();
    obj[sym] = this;
    let res = obj[sym](...args[0]);
    delete obj[sym];
    return res;
}

只需要在call的基础上做一点小改动就可以了

测试用例:

let person = {
    firstName: "Allen",
    lastName: "Wang"
}

let printName = function (city, country){
    console.log(this.firstName + " " + this.lastName + " " + city + " " + country )
}

printName.apply(person, ["Beijing", "China"]) 
// Allen Wang Beijing China
printName.myApply(person, ["Beijing", "China"]) 
// Allen Wang Beijing China

实现bind:

Function.prototype.myBind = function(obj,...args) {
    let func = this;
    return function(...args1){
        return func.apply(obj, [...args, ...args1])
    }
}

测试用例:

let person = {
    firstname: "Allen",
    lastname: "Wang"
}

let printName = function (city, country) {
    console.log(this.firstname + " " + this.lastname + " " + city + " " + country
    )
}

let Bind = printName.bind(person,"Beijing")
Bind("China")
// Allen Wang Beijing China

Function.prototype.myBind = function (obj, ...args) {
   let func = this;
   return function(...args1){
       return func.apply(obj, [...args, ...args1])
   }
}

let theBind = printName.myBind(person,"Beijing")
theBind("China")
//Allen Wang Beijing China