Overview
Implement fnApply(fn, thisArg, args) that simulates fn.apply(thisArg, args).
Constraints
- Do not use
Function.prototype.applyorFunction.prototype.call.
Examples
function greet(greeting) { return greeting + ' ' + this.name; }
fnApply(greet, { name: 'Alice' }, ['Hello']); // 'Hello Alice'Solution
Reveal solution
function fnApply(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-apply.js
Function.prototype.apply
easycodingJavaScriptFunctions
Overview
Implement fnApply(fn, thisArg, args) that simulates fn.apply(thisArg, args).
Constraints
- Do not use
Function.prototype.applyorFunction.prototype.call.
Examples
function greet(greeting) { return greeting + ' ' + this.name; }
fnApply(greet, { name: 'Alice' }, ['Hello']); // 'Hello Alice'Solution
Reveal solution
function fnApply(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