ForeveHG / Frontend-Daily-Interview

学习,尝试回答一些前端面试题
1 stars 0 forks source link

22. call、bind、apply的区别,如何实现它们 #22

Open ForeveHG opened 4 years ago

ForeveHG commented 4 years ago

call和apply的功能一样,都是根据指定this和参数来调用函数,唯一的区别就是call接受的是一个参数列表,apply接受一个包含多个参数的数组 fn.call(thisArg, arg1,arg2...) fn.apply(thisArg, [arg1,arg2...])

Function.prototype.myCall =function(context) {
    if(!context) throw new TypeError("Cannot convert undefined or null to object")
    if(typeof context != "object") context = Object.create(null)
    context.fn = this;
    let result = context.fn(...Array.from(arguments).slice(1))
    delete context.fn
    return result
}
Function.prototype.myApply=function(context) {
    if(!context) throw new TypeError("Cannot convert undefined or null to object")
    if(typeof context != "object") context = Object.create(null)
    context.fn = this;
    let result = context.fn(...arguments[1]))
    delete context.fn
    return result
}

bind方法创建一个新的函数,调用bind方法时,第一个参数作为新函数的this值,其他参数作为新函数被调用时的参数

Function.prototype.myBind = function(context) {
    let args = Array.from(arguments).slice(1)
    return function() {
        this.call(context,...args.concat(arguments))
    }
}