11/* The for principles of "this";
22* in your own words. explain the four principle for the "this" keyword below.
3- *
4- * 1.
5- * 2.
6- * 3.
7- * 4.
3+ * The 4 principles of 'this' are related to their 'this binding'
4+ * 1. 'Global Binding': This happens when a function with the 'this' keyword is called globally
5+ * 2. 'Implicit Binding': This occurs when refferencing a method or a function which is withoin an object.
6+ this are functions preceeded by a 'dot' e.g Object.functionName.
7+ * 3. 'New Binding': Whenever an instance of a constructor function is created, the 'this' refers to a specific
8+ instance of the object that is created and returned by the constructor function
9+ * 4. 'Explicit Binding': Whenever the function prototypes .call(), .apply(), .bind() is used the 'this' keyword can be explicitly set
10+ to reference any object in another context.
811*
912* write out a code example of each explanation above
1013*/
1114
1215// Principle 1
1316
1417// code example for Window Binding
18+ function sayName ( name ) {
19+ console . log ( this ) ;
20+ return name ;
21+ }
22+ sayName ( "D'Artagnan" ) ;
1523
1624// Principle 2
1725
1826// code example for Implicit Binding
27+ const myObj = {
28+ greeting : 'Hello' ,
29+ sayHello : function ( name ) {
30+ console . log ( `${ this . greeting } my name is ${ name } ` ) ;
31+ console . log ( this ) ;
32+ }
33+ } ;
34+ myObj . sayHello ( 'Ryan' ) ;
1935
2036// Principle 3
2137
2238// code example for New Binding
39+ function CordialPerson ( greeter ) {
40+ this . greeting = 'Hello ' ;
41+ this . greeter = greeter ;
42+ this . speak = function ( ) {
43+ console . log ( this . greeting + this . greeter ) ;
44+ console . log ( this ) ;
45+ } ;
46+ }
47+
48+ const jerry = new CordialPerson ( 'Newman' ) ;
49+ const newman = new CordialPerson ( 'Jerry' ) ;
50+
51+ jerry . speak ( ) ;
52+ newman . speak ( ) ;
2353
2454// Principle 4
2555
26- // code example for Explicit Binding
56+ // code example for Explicit Binding
57+ function CharacterStats ( attributes ) {
58+ GameObject . call ( this , attributes ) ;
59+ this . healthPoints = attributes . healthPoints ;
60+ }
61+
62+ CharacterStats . prototype = Object . create ( GameObject . prototype ) ;
63+
64+ CharacterStats . prototype . takeDamage = function ( ) {
65+ return `${ this . name } took damage.` ;
66+ }
67+
0 commit comments