手写apply函数

Function.prototype.myApply = function(context, args) {
    // Step 1: 判断调用对象
    if (typeof this !== 'function') {
        throw new TypeError('Type Error');
    }

    // Step 2: 获取 this
    context = context || window;

    // Step 3: 创建一个唯一的属性名
    const fnSymbol = Symbol();
    context[fnSymbol] = this;

    // Step 4: 调用这个方法
    const result = args ? context[fnSymbol](...args) : context[fnSymbol]();

    // Step 5: 删除我们新创建的方法
    delete context[fnSymbol];

    return result;
}

// 使用示例
function greet(greeting, punctuation) {
    return greeting + ', ' + this.name + punctuation;
}

let person = {name: 'John'};
console.log(greet.myApply(person, ['Hello', '!']));  // Output: 'Hello, John!'
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容