-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathApply-Polyfill.js
More file actions
45 lines (35 loc) 路 1.35 KB
/
Copy pathApply-Polyfill.js
File metadata and controls
45 lines (35 loc) 路 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* 馃挕"JavaScript-with-JC"
馃憠 apply method and Its Polyfill
apply method allows us to use the methods of another object or outside methods, apply method is used for function borrowing.
馃挕apply method takes first argument as object, and rest arguments as array.
馃挕Note - apply method executes the borrowed function immediately unlike bind ().
*/
getPlayerInfo = function (role, country) {
return `${this.firstName} ${this.lastName}, ${role} from ${country}`;
};
const player1 = {
firstName: "Virat",
lastName: "Kohli",
};
const player2 = {
firstName: "Hardik",
lastName: "Pandya",
};
console.log(getPlayerInfo.apply(player1, ["Batsman", "India"]));
console.log(getPlayerInfo.apply(player2, ["All-Rounder", "India"]));
Function.prototype.customApply = function (context, args = []) {
if (!Array.isArray(args)) {
throw new Error(
"Reminder, apply method takes array of arguments (2nd to nth)"
);
}
let currentContext = context || globalThis;
// Symbol() ensures that new method won't override existing methods of currentContext
let newProp = Symbol();
currentContext[newProp] = this;
let result = currentContext[newProp](...args);
delete currentContext[newProp];
return result;
};
console.log(getPlayerInfo.customApply(player1, ["Batsman", "India"]));
console.log(getPlayerInfo.customApply(player2, ["All-Rounder", "India"]));