Page 127 - JavaScript
P. 127

class Cow {

           constructor() {
             this.sound = "moo";
           }

           makeSoundLater() {
             setTimeout(() => console.log(this.sound), 1000);
           }
         }

         const betsy = new Cow();

         betsy.makeSoundLater();


        In the makeSoundLater() method, the this context refers to the current instance of the Cow object, so
        in the case where I call betsy.makeSoundLater(), the this context refers to betsy.


        By using the arrow function, I preserve the this context so that I can make reference to this.sound
        when it comes time to print it out, which will properly print out "moo".



        If you had used a regular function in place of the arrow function, you would lose the context of
        being within the class, and not be able to directly access the sound property.

        Arguments Object


        Arrow functions do not expose an arguments object; therefore, arguments would simply refer to a
        variable in the current scope.



         const arguments = [true];
         const foo = x => console.log(arguments[0]);

         foo(false); // -> true


        Due to this, arrow functions are also not aware of their caller/callee.

        While the lack of an arguments object can be a limitation in some edge cases, rest parameters are
        generally a suitable alternative.


         const arguments = [true];
         const foo = (...arguments) => console.log(arguments[0]);

         foo(false); // -> false


        Implicit Return


        Arrow functions may implicitly return values by simply omitting the curly braces that traditionally
        wrap a function's body if their body only contains a single expression.


         const foo = x => x + 1;
         foo(1); // -> 2



        https://riptutorial.com/                                                                               84
   122   123   124   125   126   127   128   129   130   131   132