call,apply,bind

136 阅读1分钟
Function.prototype.muCall = function(context,...args){//call
    context = Object(context) || window
    let key = Symbol('own')
    context[key] = this
    args = args || []
    let res = context[key](...args)
    delete context[key]
    return res
}
Function.prototype.muapply = function(context,args) {//apply
    //这里默认不传就是给window,也可以用es6给参数设置默认参数
    context = Object(context) || window
    args = args ? args : []
    //给context新增一个独一无二的属性以免覆盖原有属性
    const key = Symbol()
    context[key] = this
    //通过隐式绑定的方式调用函数
    const result = context[key](...args)
    //删除添加的属性
    delete context[key]
    //返回函数调用的返回值
    return result
}

Function.prototype.mubind = function(context,...args) {//bind
    const fn = this
    args = args || []
    
    return function newFn(...newFnArgs) {
        if(this instanceof newFn) {
            return new fn(...args,...newFnArgs)
        }
        return fn.apply(context,[...args,...newFnArgs])
    }
}


function sayHelloTo (to,fo) {
    console.log(`${this.name} say hello to ${to}-${fo}`)
}

var Foo = {
  name: 'Foo'
}
sayHelloTo.muCall(Foo,'a','b')
// let ca = sayHelloTo.mubind(Foo)
// ca('a','b')
//Foo say hello to Bar.