From 49fade8c3f6bc3dc8d24142f902474645a74e249 Mon Sep 17 00:00:00 2001 From: Tamiris Bonicenha Date: Tue, 8 Oct 2019 07:52:34 -0300 Subject: [PATCH 1/2] add aply --- implementations/apply.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 implementations/apply.js diff --git a/implementations/apply.js b/implementations/apply.js new file mode 100644 index 0000000..9ec3870 --- /dev/null +++ b/implementations/apply.js @@ -0,0 +1,40 @@ +/* + The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object). + + + MDN Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply + + + Parameters + + * otherThis + The value of this provided for the call to func. + * arr + Optional. An array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function. + + Return value + The result of calling the function with the specified this value and arguments. +*/ + +Function.prototype.myApply = function (otherThis, arr) { + otherThis = otherThis || global; + var uniqueID = "00" + Math.random(); + while (otherThis.hasOwnProperty(uniqueID)) { + uniqueID = "00" + Math.random(); + } + otherThis[uniqueID] = this; + + var args = []; + var result = null; + if (!arr) { + result = otherThis[uniqueID](); + } else { + for (let i = 1, len = arr.length; i < len; i++) { + args.push("arr[" + i + "]"); + } + result = eval("otherThis[uniqueID](" + args + ")"); + } + + delete otherThis[uniqueID]; + return result; +}; \ No newline at end of file From 35e5d2600af3e4f33b5999542a4d2b23d07597e4 Mon Sep 17 00:00:00 2001 From: Tamiris Bonicenha Date: Tue, 8 Oct 2019 07:54:41 -0300 Subject: [PATCH 2/2] fix last line --- implementations/apply.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/implementations/apply.js b/implementations/apply.js index 9ec3870..acf4ab3 100644 --- a/implementations/apply.js +++ b/implementations/apply.js @@ -37,4 +37,4 @@ Function.prototype.myApply = function (otherThis, arr) { delete otherThis[uniqueID]; return result; -}; \ No newline at end of file +};