InterviewSolution
Saved Bookmarks
| 1. |
What is the advantage of using the arrow syntax for a constructor method? |
|
Answer» The main benefit of utilising an arrow function as a method within a CONSTRUCTOR is that the value of this is set at the moment of function generation and cannot be changed later. As a result, WHENEVER the constructor is used to create a new OBJECT, this refers to that object. const Shape = function(shapeName) { this.shapeName = shapeName; this.showName1 = function() { console.log(this.shapeName); }; this.showName2 = () => { console.log(this.shapeName); };};const circle = new Shape('Circle');const square = new Shape('Square');circle.showName1(); // Circlecircle.showName2(); // Square// The regular function can have its 'this' value changed, but the arrow function cannotcircle.showName1.call(square); // Square (because "this" is now the square object)circle.showName2.call(square); // Circlecircle.showName1.apply(square); // Square (because 'this' is now the square object)circle.showName2.apply(square); // Circlecircle.showName1.bind(square)(); // Square (because 'this' is now the square object)circle.showName2.bind(square)(); // Circlevar showNameFromPic1 = circle.showName1;sayNameFromPic1(); // undefined (because 'this' is now the PIC object)var showNameFromPic2 = circle.showName2;showNameFromPic2(); // CircleThe major point here is that for a NORMAL function, this can be modified, but for an arrow function, the context is always the same. You won't have to worry about the context changing if you pass your arrow function around to other areas of your application. |
|