Repository navigation
Expand file tree
/
Copy paththis.js
More file actions
74 lines (57 loc) · 1.47 KB
/
Copy paththis.js
File metadata and controls
74 lines (57 loc) · 1.47 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* The for principles of "this";
* in your own words. explain the four principle for the "this" keyword below.
*
* 1.
* 2.
* 3.
* 4.
*
* write out a code example of each explanation above
*/
// Principle 1: Window Binding - window/global this points to that object
function sayName(name) {
console.log(`hello my name is ${name}`);
console.log(this);
}
sayName('Ryan');
// Principle 2: Implicit Binding - object before the dot becomes this
const myObj = {
greeting: 'hello',
sayHello: function(name) {
console.log(`${this.greeting} ${name}`);
console.log(this);
}
}
myObj.sayHello('Ryan');
const sayNameFunc = (obj) => {
obj.sayName = function () {
console.log(`Hello my name is ${this.name}`);
console.log(this);
}
};
const me = {name: 'Ryan'};
const you = {name: 'Freddy' };
sayNameFunc(me);
console.log(me);
sayNameFunc(you);
console.log(you);
me.sayName();
you.sayName();
// Principle 3: New Binding - the object where the new keyword called.
function CordialPerson(greeter) {
this.greeting = 'hello';
this.greeter = 'greeter';
this.speak = function() {
console.log(this.greeting + this.greeter);
console.log(this);
}
}
const jerry = new CordialPerson('Newman');
const newman = new CordialPerson('Jerry');
jerry.speak();
newman.speak();
console.log(jerry);
console.log(newman);
// Principle 4: Explicit Binding - Whenever javascript's call or apply method is used, this is explicitly
jerry.speak.call(newman);
newman.speak.apply(jerry);