Skip to content

Commit 7b31a31

Browse files
sofialevinsofialevin
authored andcommitted
Completed this.js.
1 parent 33d1564 commit 7b31a31

1 file changed

Lines changed: 58 additions & 5 deletions

File tree

assignments/this.js

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
11
/* The for principles of "this";
22
* in your own words. explain the four principle for the "this" keyword below.
33
*
4-
* 1.
5-
* 2.
6-
* 3.
7-
* 4.
4+
* 1. Global binding
5+
6+
When a function is called in the global scope its context will be the window/console.
7+
8+
* 2. Implicit binding
9+
10+
With implicit binding you look to the left of the function call to see what its context is.
11+
12+
* 3. New binding
13+
14+
When a function is called with the "new" keyword its context is the new object being created by the constructor function.
15+
16+
* 4. Explicit binding
17+
18+
With explicit binding you tell the function what its context is going to be, with either call(), apply() or bind().
819
*
920
* write out a code example of each explanation above
1021
*/
@@ -13,14 +24,56 @@
1324

1425
// code example for Window Binding
1526

27+
function test() {
28+
console.log(this);
29+
}
30+
31+
test();
32+
1633
// Principle 2
1734

1835
// code example for Implicit Binding
1936

37+
const me = {
38+
name: 'Sofia',
39+
age: 32,
40+
hobbies: 'knitting',
41+
sayHello: function() {
42+
console.log(`Hello, I'm ${this.name}, I'm ${this.age} and I like ${this.hobbies}.`);
43+
}
44+
}
45+
46+
me.sayHello();
47+
2048
// Principle 3
2149

2250
// code example for New Binding
2351

52+
function Person(name, age, hobbies) {
53+
this.name = name;
54+
this.age = age;
55+
this.hobbies = hobbies;
56+
this.sayHello = function() {
57+
console.log(`Hello, I'm ${this.name}, I'm ${this.age} and I like ${this.hobbies}.`);
58+
}
59+
}
60+
61+
const sofia = new Person('Sofia', 32, 'knitting');
62+
63+
sofia.sayHello();
64+
2465
// Principle 4
2566

26-
// code example for Explicit Binding
67+
// code example for Explicit Binding
68+
69+
const sayHello = function() {
70+
console.log(`Hello, I'm ${this.name}, I'm ${this.age} and I like ${this.hobbies}.`);
71+
}
72+
73+
const me = {
74+
name: 'Sofia',
75+
age: 32,
76+
hobbies: 'knitting',
77+
}
78+
79+
sayHello.call(me);

0 commit comments

Comments
 (0)