美文网首页
实现call、bind、apply

实现call、bind、apply

作者: 逆风飘游的鱼 | 来源:发表于2019-10-14 13:48 被阅读0次

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

      本文链接:https://www.haomeiwen.com/subject/iyzmyctx.html