欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js 手写 call apply bind

程序员文章站 2022-03-08 09:43:39
...

call

let obj = {
    name: 'xxx'
}

function sayName(prev) {
    console.log(prev, this.name)
}

Function.prototype.myCall = function (context) {
    context = context || window;
    let args = [...arguments].slice(1)
    context.fn = this;
    let result = context.fn(...args)
    /**
     * 刚开始上面这两行我会疑惑,既然 context.fn = this 那么 context.fn(...args) 是不是等价于 this(...args) 呢
     * 可以试一下 其实不是这样的
     * context.fn(...args) ,在这里 fn 函数调用者是 context,所以函数内部的 this 指向 context 
     * this(...args)  在这里调用的是 this 函数,this 前面没有调用者,默认是 window,所以函数内部的 this 指向 window
     */
    return result
}

sayName.call(obj, 'hello,')
sayName.myCall(obj, 'hello,')

apply

let obj = {
    name: 'xxx'
}

function sayName(prev) {
    console.log(prev, this.name)
}

Function.prototype.myApply = function (context) {
    context = context || window;
    let args = arguments[1]
    context.fn = this;
    let result = context.fn(...args)
    return result
}

sayName.apply(obj, ['hello,'])
sayName.myApply(obj, ['hello,'])

bind

let obj = {
    name: 'xxx'
}

function sayName(prev) {
    console.log(prev, this.name)
}

Function.prototype.myBind = function (context) {
    context = context || window;
    let args = [...arguments].slice(1);
    context.fn = this;
    return function () {
        context.fn(...args)
    }
}

let aaa = sayName.bind(obj, 'hello,')
aaa();
let bbb = sayName.myBind(obj, 'hello,')
bbb();