Bind自己实现

49 阅读1分钟

bind

Function.prototype.bind = function (context) {
    const fn = this
    const symbolKey = Symbol()
    Object.defineProperty(context, symbolKey, {
        get: function () {
            return fn
        }
    })
    return function (...args) {
        return context[symbolKey](args)
    }
}

// 测试
function aa() { console.log(this) }
var obj = { a: 1 }
var bb = aa.bind(obj)
console.log(bb())
console.log(obj)

但是有个问题是,context上面会增加一个属性,这个还不知道有没有优化方法

call

Function.prototype.call = function (context,...args) {
    return this.bind(context)(...args)
}

或者

Function.prototype.call = function (context,...args) {
    const fn = this
    const symbol = Symbol()
    context[symbol] = fn
    const result = context[symbol](...args)
    delete context[symbol]
    return result
}

但是有个问题是,this对象指向的是 Object.create(context),而不是context,否则context上面会增加一个属性,这个还不知道有没有优化方法

apply

function.prototype.apply = function(context,args){
	return this.bind(context)(...args)
}

或者

Function.prototype.apply = function (context,args) {
    const fn = this
    const symbol = Symbol()
    context[symbol] = fn
    const result = context[symbol](...args)
    delete context[symbol]
    return result
}