© Russ Ferguson and Keith Cirkel 2017
Russ Ferguson and Keith CirkelJavaScript Recipes10.1007/978-1-4302-6107-0_17

17. Working with Classes

Russ Ferguson and Keith Cirkel2
(1)
Ocean, New Jersey, USA
(2)
London, UK
 

How Do You Make a Class in JavaScript?

Problem

How do you create a class using either ECMAScript 5 or ECMAScript 6?

Solution

JavaScript is a prototype-based language, therefore its use of inheritance is also prototype-based. ECMAScript 5 uses functions to make classes. ECMAScript 6 introduces the class keyword as syntactical sugar for class creation in JavaScript.

The Code

//ECMAScript 5 class
var Human = (
        function Human(name){
                 this.name = name;
        }
)
Human.prototype.sayGoodNight = function(){
       return 'Say Goodnight ' + this.name;
}
var george = new Human('Gracie');
console.log(george.sayGoodNight());
//ECMAScript 6 class
class Greeting{
          constructor(name){
                  this.name = name;
          }
          sayHello(){
                  return 'Hellooo ' + this.name;
          }
}
var yakko = new Greeting('Nurse!');
console.log(yakko.sayHello());
Listing 17-1.
Creating an ES5 Class and an ES6 Class

How It Works

If you come from a language like Java, Python, or any other language that is what we call class-based, then you will find that JavaScript works a little differently.
JavaScript uses what is called prototypical inheritance to provide access to methods and properties found in other objects. Each object contains a prototype object with a reference to another object up until an object’s prototype has a null value. At this point, you have reached the end of the chain and there are no other objects to inherit from.
The first example shows how function objects can be used to create a class. Here we use a function expression and assign it to a variable; inside the function property names are created and given value based on the argument passed to the function.
The next section is where the prototypical inheritance comes in. Function objects like other JavaScript objects have a prototype property. However, the function’s prototype does not link to another object. We then assign new functions to the object that can be used with other instances of that objects.
With functions assigned to the prototype, you can access internal properties to the object (in this case, the name property) and a separate instance can be developed by using the new operator .
The second example is the ECMAScript 6 version of how to create a class. The result is the same as the ES5 version, but this uses syntactical sugar to achieve similar results.
One if the things that may stick out is the use of a constructor function . In this class declaration, the constructor is a special method that can accept properties when initializing an object. If it’s declared more than once, a SyntaxError will be thrown. Creating an instance is exactly the same as what someone would be used to. Because of the prototypical nature of JavaScript, if a method or property gets changed in the class, the instance is also updated.
Class declarations like in this example are not hoisted. Because of this, be sure to declare the class you want to use before trying to access it. Not doing so will return a ReferenceError.

How Does the ES6 Class Keyword Work with Prototypal Inheritance ?

Problem

You want to know if JavaScript is using class-based inheritance now that it has the class keyword.

Solution

JavaScript is not a class-based language like Java. This can make the ES6 Class keyword confusing. This keyword hides the prototypical inheritance that JavaScript is based on and provides a way to create objects that would be familiar to developers coming from class-based languages.

The Code

//ES5 Class Creation
function Show(name, network){
         this.name = name;
         this.network = network;
};
Show.prototype.getShowName = function getShowName(){
       return this.name;  //added to the Show prototype it now has access to it's properties.
};
Show.prototype.getShowNetwork = function getShowNetwork(){
       return this.network;
};
var gravityFalls = new Show('Gravity Falls', 'Disney XD');
console.log(gravityFalls.getShowName());  //returns Gravity Falls
console.log(gravityFalls.getShowNetwork()); //returns Disney XD
Show.prototype.getShowNetwork = function getShowNetwork(){
       return 'On My TV!';
};
console.log(gravityFalls.getShowNetwork()); //returns On My TV!
console.log(Show.prototype); //shows getShowName and getShowNetwork functions are now part of the Show prototype
//ES6 Class Creation
class MyTVShow{
    constructor(name, network){
          this.name = name;
          this.network = network;
    }
   getShowName(){
          return this.show;
    }
   getShowNetwork(){
          return this.network;
   }
}
console.log(MyTVShow.prototype)
//shows getShowName and getShowNetwork functions are now part of the MyTVShow prototype.
Listing 17-2.
In the ES5 and ES6 Examples, All the Methods Are Added to the Prototype

How It Works

It is important to understand that class-based inheritance is very different from prototypical inheritance. In a class-based language like Java, a class will inherit or extend another class. This creates a a hierarchy between classes. The new class will be a subclass of the original or parent class. One of the benefits is that you now gain all the functionality of the parent class in addition to the functions of the child class.
With JavaScript inheritance is maintained by using the prototype property . Every object contains a prototype property that references another object. This is called the prototype chain. Even when using the keywords class, constructor, static, extends, and super, JavaScript remains prototype-based. Because the prototype can reference other objects, you can be more flexible than with the class-based approach.
Listing 17-2 is similar to Listing 17-1; however, we can get more into the details of how it works. The function Show at this moment does not have anything assigned to its prototype. The next two lines define functions that will now become methods to the class. When assigning functions to the prototype, every instance based on this class will now inherit these properties.
After retrieving the results in the log, we reassign the method getShowNetwork . Here, we can see that the result returned from the method is different than it was originally.
The last line of the first example shows the result of the Show class prototype. When looking at the console in your browser, you can see the both previous functions are part of the prototype object.
The ES6 example is a condensed version of the first example. Here we have less code to achieve the same result. To illustrate that the results are the same , the last line also shows the prototype object in the browser console. If you were to compare the results of both objects, they would both contain the methods needed in the prototype object.

How Do You Assign Getters and Setters to a ES6 Class ?

Problem

You want to be able to quickly get and set properties using the ES6 syntax.

Solution

Similar to class-based languages, ES6 allows for the creation of getter and setters properties for objects.

The Code

class Cookies{
        constructor(){
                this._typeOfCookie;
        }
        set cookieType(typeOfCookie){
                this._typeOfCookie = typeOfCookie;
        }
        get cookieType(){
                return this._typeOfCookie;
        }
}
var myCookie = new Cookies();
        myCookie.cookieType = "Chocolate Chip";
        console.log(myCookie.cookieType); //returns Chocolate Chip;
        console.log(myCookie._typeOfCookie);
Listing 17-3.
Using Getters/Setters in an ES6 Class

How It Works

Getters and setters allow you to access properties inside a class without talking to the property directly. The way that it works in ES6 is that the syntax is bound to a function that will look up the property when called. In Listing 17-3, we create a class and inside set up a get and set keyword that point to a function called cookieType. When assigning a value, we use the equals sign (=). This will be used by the set method since we are setting a value. When retrieving a result, we just point to the property and the get method will retrieve the inner value of _typeOfCookie.
It is important to note that, in this case, the underscore (_) is just the developer’s way to signaling to other developers not to access this property directly. It does not really keep this property private.

What Do the Extend and Super Keywords Do ?

Problem

You want to know what the purpose of extending a class is and why you need the keyword super.

Solution

The extends keyword is used to create a subclass or child class of an existing class.

The Code

class Robot{
        constructor(){
                this.type;
        }
}
class BendingUnit extends Robot {
               constructor(){
                super();
                this.name;
                this.occupation = 'Industrial Robot';
                this.origin = 'Tijuana, Mexico';
        }
}
class AstromechDroid extends Robot{
        constructor(){
                super();
                this.name;
        }
}
var bender = new BendingUnit();
             bender.type = 'Bending Unit 22';
             bender.name = 'Bender Bending Rodriguez';
             console.log(bender.type);  //returns Bending Unit 22
             console.log(bender.name);  //returns Bender Bending Rodriguez
var r2d2 = new AstromechDroid();
           r2d2.type = 'Astromech Droid';
           r2d2.name = 'R2-D2';
           console.log(r2d2.type);  //returns Astromech Droid
           console.log(r2d2.name);  //returns R2-D2
Listing 17-4.
Using the Extends Keyword to Make Child Classes

How It Works

Like in other class-based languages, the extends keyword allows the current class to inherit properties and methods from another class. When declaring a class that will need properties from another class, the keyword extends is provided in the definition with the name of the class it is extending.
The child class must then use the super keyword to access any properties of the now parent class. If values need to be passed to the parent class to prevent any errors, they can be used as parameters of the super function call.
In Listing 17-4, we have two child classes, BendingUnit and AstromechDroid. Both of these classes extend Robot. Because of this, both instances of these classes have a property called type . This property is inherited because of using the extends keyword. After the instance has been created, a developer can use the type property as if it were native to the child class.
In each case with the child classes, the Robot class becomes the prototype object. This is because of the prototypical nature of JavaScript. Subclasses can also extend built-in objects like the Date object.

What Are Static Methods ?

Problem

You want to know how static methods are different than regular methods in a class.

Solution

Static methods do not need the class to be instantiated in order to use them.

The Code

class Human{
        constructor(){
        }
        static hasLegs(){
                 return 'Person has legs';
        }
        static hasAmrs(){
                 return 'Person has arms';
        }
}
console.log(Human.hasLegs())  //returns Person has legs
console.log(Human.hasAmrs())  //returns Person has arms
Listing 17-5.
Static Methods Are Called Directly from the Class

How It Works

Static methods can be used without instantiation of an instance of a class. A similar example would be the Math class. Instances cannot be made of the Math class. If an instance is created with a class that uses static methods, these methods cannot be called.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.42.134