手写call

194 阅读1分钟

1、手写

 Function.prototype.call = function call(context, ...params) {
    // this(self)->fn  context->obj  params->[10,20]
    context == null ? context = window : null;
    if (!/^(object|function)$/i.test(typeof context)) context = Object(context);
    let self = this,
        key = Symbol('KEY'),
        result;
    context[key] = self;
    result = context[key](...params);
    delete context[key];
    return result;
};


面试:

Function.prototype.call = function (context, ...args) {
    var key = Symbol('key')
    context[key] = this
    var result = context[key](...args)
    delete context[key]
    return result
}

2、题目

 var name = '珠峰培训';

function A(x, y) {
    var res = x + y;
    console.log(res, this.name);
}

function B(x, y) {
    var res = x - y;
    console.log(res, this.name);
}
B.call(A, 40, 30);
B.call.call.call(A, 20, 10);
Function.prototype.call(A, 60, 50);
Function.prototype.call.call.call(A, 80, 70);