-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcall-apply-bind.js
79 lines (63 loc) · 1.45 KB
/
call-apply-bind.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
function Person(name) {
this.name = name;
console.log(this); // Person {}
}
const temi = new Person('Temi');
console.log(temi.name); // Temi
class PersonClass {
constructor(name) {
this.name = name;
console.log(this); // PersonClass { name: 'Temi' }
}
}
const temi2 = new PersonClass('Temi');
console.log(temi2.name); // Temi
function add(a, b, c) {
console.log(a, b, c)
// anytime we do not have value for this in a function or object,
// the value will be the global window variable
// globalThis - node || window - browser
console.log(this)
}
// add.call({ name: 'Temi' }); // { name: 'Temi' }
add.call({ name: 'Temi' }, 1, 2, 3);
add.apply({ name: 'Temi' }, [1, 2]);
let demon = {
a: 1,
b: 2,
add() {
console.log(this.a + this.b);
return this.a + this.b;
}
}
const fire = {
...demon,
a: 10,
b: 20
}
const water = {
...demon,
a: undefined,
b: undefined
}
console.log(water)
water.add.call({a: 99, b: 1})
// water.add.apply({a: 99, b: 1})
fire.add(); // 30
demon.add(); // 3
const module2 = {
x: 42,
getX: function () {
return this.x;
},
};
const unboundGetX = module2.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// Expected output: undefined
const boundGetX = unboundGetX.bind(module2);
console.log(boundGetX());
NodeList.prototype.on = NodeList.prototype.addEventListener = function (name, fn) {
this.forEach(function (elem, i) {
elem.on(name, fn);
});
}