forked from bloominstituteoftechnology/JavaScript-III
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththis.js
More file actions
57 lines (45 loc) · 1.6 KB
/
this.js
File metadata and controls
57 lines (45 loc) · 1.6 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
/* The for principles of "this";
* in your own words. explain the four principle for the "this" keyword below.
*
* 1. Principle one is where this is bound to the window, typically in situations where this has not been implicitly or explicitly specified or created with a new statement.
* 2. Implicit binding is where an object is created and this is generally implicit to the object definition specified at design time.
* 3. New binding generally takes effect when the object constructor is called and instanciated. This is generally at run time, throughout the lifecycle of the scope.
* 4. Explicit binding is where this is specifically defined on a function or object, with its parameters, using inbuilt functions like call, apply and bind, each having separate params.
*
* write out a code example of each explanation above
*/
// Principle 1
// code example for Window Binding
function Welcome(){
return this; //example
}
// Principle 2
// code example for Implicit Binding
const obj = {
name: "Dan",
position: "Instructor",
speak: function(){
return `${this.name} says hi.`
}
}
// Principle 3
// code example for New Binding
function Vehicle(obj){
this.model = obj.model;
this.year = obj.year;
}
const bmw = new Vehicle({model: "X5", year: 2019});
// Principle 4
// code example for Explicit Binding
function Car(obj){
this.model = obj.model;
this.year = obj.year;
}
function aiCar(obj){
if(obj.year === 2019){
return `This car is autonomous.`;
}
return `Get a 2019 car!`;
}
const mercedes = new Car({model: "X5", year: 2019});
aiCar.apply(mercedes, objProp)