-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path61.Function_prototype_call.js
50 lines (47 loc) · 2 KB
/
61.Function_prototype_call.js
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
46
47
48
49
50
// CALL POLYFILL
// args is arguments one by one
Function.prototype.mycall = function (context, ...args) {
// you tie a function into an object(context) as if it belonged to the object
const symbol = Symbol(); // create unique key
context = Object(context || window); // set context to windows if null and Create an object to handle primitive values
// 'this' points to the calling function here
context[symbol] = this; // assign the function to a unique method created on the context
const result = context[symbol](...args); // call the function
delete context[symbol]; // delete the unique key
return result; // return result
};
// BIND POLYFILL
// bind returns a func which when called behave like apply, call
Function.prototype.mybind = function (context, ...args) {
const symbol = Symbol();
context[symbol] = this;
return function (...newArgs) {
const result = context[symbol](...args,...newArgs); // call the function
delete context[symbol]; // delete the unique key
return result; // return result
};
};
// APPLY POLYFILL
// code exact same as call just the args is an array here so need to destruct(...)
Function.prototype.myapply = function (context, args) {
// you tie a function into an object(context) as if it belonged to the object
const symbol = Symbol(); // create unique key
context = Object(context || window); // set context to windows if null and Create an object to handle primitive values
// 'this' points to the calling function here
context[symbol] = this; // assign the function to a unique method created on the context
const result = context[symbol](...args); // call the function
delete context[symbol]; // delete the unique key
return result; // return result
};
// Testing
let obj = {
a: 10,
b: 20,
};
function tester(a, b) {
return `a: ${this.a} and b: ${this.b} | curr args a: ${a} and b: ${b}`;
}
console.log(tester.mycall(obj, 30, 40));
const bindFunc = tester.mybind(obj, 30, 40);
console.log(bindFunc());
console.log(tester.myapply(obj, [30, 40]));