Overview
Implement fnCall(fn, thisArg, ...args) that simulates fn.call(thisArg, ...args).
Constraints
- Do not use
Function.prototype.callorFunction.prototype.apply.
Examples
function greet(greeting) { return greeting + ' ' + this.name; }
fnCall(greet, { name: 'Bob' }, 'Hi'); // 'Hi Bob'Solution
Reveal solution
function fnCall(fn, thisArg, ...args) {
const ctx = Object(thisArg);
const key = Symbol();
ctx[key] = fn;
const result = ctx[key](...args);
delete ctx[key];
return result;
}function-prototype-call.js
Function.prototype.call
easycodingJavaScriptFunctions
Overview
Implement fnCall(fn, thisArg, ...args) that simulates fn.call(thisArg, ...args).
Constraints
- Do not use
Function.prototype.callorFunction.prototype.apply.
Examples
function greet(greeting) { return greeting + ' ' + this.name; }
fnCall(greet, { name: 'Bob' }, 'Hi'); // 'Hi Bob'Solution
Reveal solution
function fnCall(fn, thisArg, ...args) {
const ctx = Object(thisArg);
const key = Symbol();
ctx[key] = fn;
const result = ctx[key](...args);
delete ctx[key];
return result;
}NameTopicDifficulty
103 of 103 problems