Javascript Class Tutorial Example

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will create a Shape class as an example which has a “sides” property that is initialized by the constructor…

We create a new Shape instance and it prints out “3” as expected.

Static method in Javascript

We can add a static variable called “count” and a static method called “numShapes”. These can be invoked without creating an instance of the class…

And they are referenced by using the class name “Shape”

getter and setter in Javascript classes

Now we create a “color” property which can be access via a getter and setter…

Note that internally, we had to store this color in variable _color (with underscore). This is because we want our setter and getter to be “color”. The backing variable can not be named the same (or you get infinite loop).

The underscore is by convention, it does not protect the variable from being accessed directly.

Derived Classes in Javascript

Given our Shape class, we can derive a Square class from it using the extends keyword…

class Square extends Shape {
constructor(sides, length) {
super(sides);
this.length = length;
}
}
let myBox = new Square(4, 10);
console.log(myBox);

If the Shape class had a method call “speak”. The derived class can call that method with “super.speak()”


Related Posts

Tags

Share This