-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallBindApply.js
More file actions
60 lines (40 loc) · 1.31 KB
/
callBindApply.js
File metadata and controls
60 lines (40 loc) · 1.31 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Explicitly binding
let user = { name: "sudhakar" };
function printName(age) {
console.log(this.name, +age);
}
// as here this refers to window object.
// For every function call apply bind is available
printName();
printName.call(user, 24); // here first praram is obj and next params are argumnents of function
printName.apply(user, [24]); // apply is same as call where in call args are passed individudally but in apply as array
const bindFunc = printName.bind(user); // bind will create new function with binding the object with function
bindFunc(24);
// call polyfill
Function.prototype.myCall = function (context = {}, ...args) {
if (typeof this !== "function") {
throw new Error("it should be function");
}
context.fn = this;
context.fn(...args);
};
printName.myCall(user, 24);
// apply polyfill
Function.prototype.myApply = function (context = {}, [args]) {
if (typeof this !== "function") {
throw new Error("it should be function");
}
context.fn = this;
context.fn([args]);
};
printName.myApply(user, [24]);
// bind polyfill
Function.prototype.myBind = function (context = {}, ...args) {
if (typeof context !== "function") {
throw new Error("it should be a function");
}
return function (...newArgs) {
context.fn = this;
context.fn(...args, ...newArgs);
};
};