forked from bloominstituteoftechnology/JavaScript-III
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththis.js
More file actions
76 lines (57 loc) · 1.72 KB
/
Copy paththis.js
File metadata and controls
76 lines (57 loc) · 1.72 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
75
76
/* The for principles of "this";
* in your own words. explain the four principle for the "this" keyword below.
*
* 1. Without context/constraints 'this' binds globally to the console
* 2. When calling a function with dot notation, the object before the dot is what 'this' points to.
* 3. When using the 'new' keyword to invoke a function, the child inherits the parent.
* 4. When you use the 'call' or 'apply' method, you are telling 'this' exactly what to point to (what's in the parentheses).
*
* write out a code example of each explanation above
*/
// Principle 1
// code example for Window Binding
function someFunc(example) {
console.log(this);
return example;
}
someFunc("My Example");
// Principle 2
// code example for Implicit Binding
const anObj = {
sayGoodbye: "Goodbye, ",
goodbyeFunc: function(name) {
console.log(`${sayGoodbye} ${name}`);
console.log(this);
}
};
anObj.goodbyeFunc('Alex');
// Principle 3
// code example for New Binding
function CordialPerson(person) {
this.greeting = 'Good day, ';
this.person = person;
this.speak = function() {
console.log(this.greeting + this.person);
console.log(this);
};
}
const brandon = new CordialPerson('Alex');
const alex = new CordialPerson('Brrandon');
brandon.speak();
alex.speak();
// Principle 4
// code example for Explicit Binding
function CordialPerson(person) {
this.greeting = 'Good day, ';
this.person = person;
this.speak = function() {
console.log(this.greeting + this.person);
console.log(this);
};
}
const brandon = new CordialPerson('Alex');
const alex = new CordialPerson('Brrandon');
brandon.speak();
alex.speak();
brandon.speak.call(alex);
alex.speak.call(brandon);