模拟apply实现

/**
* 模拟apply实现
*/
Function.prototype.newApply = function (context, argArray) {
    // 如果调用者不是方法抛出异常
    if (typeof this !== 'function') {
        throw new TypeError('调用者不是一个方法');
    }
    // 判断参数是否为null或者undefined
    if (typeof argArray === 'undefined' || typeof argArray === null) {
        argArray = [];
    }
    // 判断参数是否是对象
    if (!(argArray instanceof Object)) {
        throw new TypeError('参数要是对象');
    }
    // 外面传入的context的值会修改并成为this的值
    if (typeof context === 'undefined' || context === null) {
        context = window;
    }
    context.fn = this;
    let result = context.fn(...argArray);
    delete context.fn;
    return result;
}
var name = '吕洞宾';
function fn () {
    console.log(this.name);
    console.log(arguments);
}
const person = {
    name: '铁拐李'
}
fn.newApply(person, [1, 2, 3]);

参考资料

  1. www.jianshu.com/p/7f43b611f…

微信公众号“前端那些事儿”

发布了71 篇原创文章 · 获赞 43 · 访问量 79万+

猜你喜欢

转载自blog.csdn.net/cengjingcanghai123/article/details/104447356