面试--手写实现call, apply, bind函数

call函数

let obj = {value: 'hah'}

function test(name) {
    console.log('我是' + name + this.value)
}

Function.prototype.myCall = function(thisArg, ...args) {
    thisArg.fn = this; // thisArg是obj变量,...args是剩余其他参数
    let result = thisArg.fn(...args);
    delete thisArg.fn;
    return result;
    
}

test.myCall(obj, 'li')

apply函数

let obj = {value: 'hah'}
function test(name) {
    console.log('我是' + name + this.value)
}
Function.prototype.myApply = function(thisArg, args) {
    thisArg.fn = this; // obj是obj变量,...args是剩余其他参数
    let result;
    if (args) {
        result = thisArg.fn(...args)
    } else {
        result = thisArg.fn()
    }
    delete thisArg.fn;
    return result;
    
}
test.myCall(obj, 'li')

bind函数 

let obj = {value: 'hah'}
function test(name) {
    console.log('我是' + name + this.value)
}
Function.prototype.myBind = function (thisArg, ...arg) {
     let self = this
     return function () {
         self.apply(thisArg, [...arg])
     }
 }

let aa = test.myBind(obj, 'li');
aa()

你可能感兴趣的:(前端,bind,js)