forked from bloominstituteoftechnology/JavaScript-II-Mini
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththis.js
More file actions
64 lines (53 loc) · 1.37 KB
/
this.js
File metadata and controls
64 lines (53 loc) · 1.37 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
/* The for principles of "this";
* in your own words. explain the four principle for the "this" keyword below.
*
* 1. Window Binding - 'this' keyword points to the Global scope by default.
* 2. Implicit Binding - Object before the '.' (dot) will become 'this'.
* 3. New binding - using the 'new' keyword
* 4. Explicit Binding - using the call, bind and apply methods.
*
* write out a code example of each explanation above
*/
// Principle 1
// code example for Window Binding
console.log(this);
// Principle 2
// code example for Implicit Binding
const myObj = {
greeting: 'Hello',
sayHello: function (name) {
console.log(`${this.greeting} ${name}`);
console.log(this);
}
};
myObj.sayHello("William");
// Principle 3
// code example for New Binding
class User {
constructor(name) {
this.name = name;
}
getName () {
console.log(`New user's name is ${this.name}`);
}
}
const newUser = new User("William");
newUser.getName();
// Principle 4
// code example for Explicit Binding
function Animal(options) {
this.name = options.name;
}
Animal.prototype.grow = function () {
console.log(`${this.name} grew larger`);
};
function Cat(options) {
// invoke Animal here with .call
Animal.call(this, options);
}
Cat.prototype = Object.create(Animal.prototype);
const foofie = new Cat({
name: 'foofie',
});
//
foofie.grow();