Repository navigation
Expand file tree
/
Copy paththis.js
More file actions
58 lines (44 loc) · 1.46 KB
/
Copy paththis.js
File metadata and controls
58 lines (44 loc) · 1.46 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
/* The for principles of "this";
* in your own words. explain the four principle for the "this" keyword below.
*
* 1. Window/Global Object Binding: When in the global scope, the value of “this” will be the window/console Object
* 2. Implicit Binding: Whenever a function is called by a preceding dot, the object before that dot is this.
* 3. New binding: Whenever a constructor function is used, this refers to the specific instance of the object that is created and returned by the constructor function.
* 4. Explicit binding: Whenever JavaScript's call or apply method is used, this is explicitly defined.
*
* write out a code example of each explanation above
*/
// Principle 1
// code example for Window Binding
function sayName(name) {
console.log(this);
return name;
}
sayName("D'Artagnan");
// Principle 2
// code example for Implicit Binding
const myObj = {
greeting: 'Hello',
sayHello: function(name) {
console.log(`${this.greeting} my name is ${name}`);
console.log(this);
}
};
myObj.sayHello('Ryan');
// Principle 3
// code example for New Binding
function CordialPerson(greeter) {
this.greeting = 'Hello ';
this.greeter = greeter;
this.speak = function() {
console.log(this.greeting + this.greeter);
// console.log(this);
};
}
const newman = new CordialPerson('Jerry');
newman.speak();
// Principle 4
// code example for Explicit Binding
// building on top of #3
const jerry = new CordialPerson('Newman');
newman.speak.call(jerry)