实现call、bind、apply

Function.prototype.mycall = function (context) {

    let fn = Symbol()

    context = context || window

    context[fn] = this

    let arg = [...arguments].slice(1)

    context[fn](...arg)

}

Function.prototype.myApply = function (context) {

    let fn = Symbol()

    context = context || window

    context[fn] = this

    let arg = [...arguments].slice(1)

    context[fn](arg)

}

Function.prototype.binds = function (context) {

    let self = this

    let arg = [...arguments].slice(1)

    return function () {

        let newArg = [...arguments]

        return self.apply(context, arg.concat(newArg))

    }

}

let Person = {

    name: 'Tom',

    say(age, g) {

        console.log(`我叫${this.name}我今年${age}++++${g}`)

    }

}

Person1 = {

    name: 'Tom1'

}

Person.say.mycall(Person1, 20000, 222, 445)//我叫Tom1我今年18

Person.say.myApply(Person1, [20000, 222, 445])//我叫Tom1我今年18

let fn = Person.say.binds(Person1, 20000, 222, 445)

fn()

你可能感兴趣的:(实现call、bind、apply)