Just JavaScript - ES2015 Class |
Written by Ian Elliot | |||
Monday, 12 February 2018 | |||
Page 2 of 2
Private Methods and DataWhat about private methods and variables? Although there is no provision for private entities in the class syntax i.e. no private keyword, you can still declare variables in the constructor and rely on closure to make them available to instance methods. For example:
The private variable z is available to the instance method display because of the closure. Notice that private variables are not available to prototype methods as these do not have access to the closure.
SummaryThere are three types of method you can define using class:
There is also a fourth type of method which is not supported by the class syntax but still works:
Extends – Inheritance The Class Way ES2015There are a number of ways of implementing inheritance in JavaScript as well as simply using the prototype chain. The class syntax formalizes one particularly attractive way of inheriting methods and properties from existing objects in the extends keyword. The idea is that you can use a class or a constructor as if it was a more traditional class and inherit it as the basis for building an extended class. For example suppose we start off with a simple Point class:
we could use this to create a 3D Point class by adding a z coordinate. To do this we can create the new class Point3D that extends Point:
There are two new keywords being used – extends and super. The extends keyword makes Point the base for the new class. The super keyword calls the base class constructor and sets this to reference the new instance. Obviously you cannot use this until after you have called super. That is, the above is equivalent to:
You can see that where normally this is set to {} which is then expanded by having properties added to it in this case this is set to an instance of Point which likewise has properties added to it. You could say that the null object {} is the default base class but by calling super you use an instance of an existing class. Of course, you can make use of the prototype object of the base instance to define new prototype methods as well as static methods. Notice that static methods are not inherited by the constructor. The point is that everything works in exactly the way described in the previous section. The only difference is that instead of starting from an empty object i.e. {} you start from an instance of the base class. Overall this is a harmless addition to JavaScript, but it isn't a reason for not understanding the way it all works. This is an extract from the book Just JavaScript by Ian Elliot. Buy Now: from your local AmazonJust JavaScript
|
|||
Last Updated ( Tuesday, 27 February 2018 ) |