JavaScript 自定义call,apply,bind

JavaScript 自定义call,apply,bind

call() 方法

call() 方法是预定义的 JavaScript 方法。
它可以用来调用所有者对象作为参数的方法。
通过 call(),您能够使用属于另一个对象的方法。

注意:globalThis为新增的,全局属性 globalThis 包含全局的 this 值,类似于全局对象(global object)。
所有流行的浏览器,包括Chrome 71+、Firefox 65+和Safari 12.1+,都已经支持这项功能。你也可以在Node.js 12+中使用它。

Function.prototype.myCall = function(context = globalThis, ...args) {
    
    
    if (typeof this !== "function") {
    
    
        throw new TypeError("not funciton");
    }
    // 为content添加一个临时对象fn,辅助调用this(函数)
    context.fn = this
    let res = context.fn(...args)
    delete context.fn
    return res
}

使用

function add(a, b) {
    
    
    return a + b + this.c
}
let obj = {
    
    
    c: 1
}
window.c = 2
globalThis.c = 3
console.log(add.myCall(obj, 1, 2)) //4
console.log(add.myCall(window, 1, 2)) //6   window.c被globalThis.c覆盖,否则为5
console.log(add.myCall(undefined, 1, 2)) //6

apply() 方法

Function.prototype.myApply = function (context = globalThis, args) {
    
    
    if (typeof this !== "function") {
    
    
        throw new TypeError("not funciton");
    }
    // 为content添加一个临时对象fn,辅助调用this(函数)
    context.fn = this
    let res
    // 相较于 call 多了个判断数组的过程
    if (Array.isArray(args)) {
    
    
        res = context.fn(...args);
    } else {
    
    
        res = context.fn();
    }
    delete context.fn
    return res
}

使用

function add(a, b) {
    
    
    return a + b + this.c
}
let obj = {
    
    
    c: 1
}
window.c = 2
globalThis.c = 3
console.log(add.myApply(obj, [1, 2])) //4
console.log(add.myApply(window, [1, 2])) //6   
console.log(add.myApply(undefined, [1, 2])) //6

bind()方法

Function.prototype.myBind = function(context = globalThis, ...args) {
    
    
    if (typeof this !== "function") {
    
    
        throw new TypeError("not funciton");
    }
    const _this = this
    return function(...args1) {
    
    
        return _this.call(context, ...args, ...args1)
    }
}

使用

function add(a, b) {
    
    
    return a + b + this.c
}
let obj = {
    
    
    c: 1
}
window.c = 2
globalThis.c = 3
console.log(add.myBind(obj, 1, 2)()) //4
console.log(add.myBind(window, 1, 2)()) //6   
console.log(add.myBind(window)(1, 2)) //6   
console.log(add.myBind(undefined, 1, 2)()) //6

猜你喜欢

转载自blog.csdn.net/weixin_44523860/article/details/113729906
今日推荐