JavaScript is an object orient language but programmers have dealt with objects directly without a class. Constructor functions and the “prototype” object have been used to create an object. Now with ES2015, a class finally is with us.
1. Constructor Functions and Prototype Object
As a JavaScript developer, you are familiar with the following code.
var Product = function (n, p) { this.name = n; this.price = p; } Product.prototype = { showInfo: function () { return this.name + ': $' + this.price; } }; var product = new Product("Pizza", 10); console.log(product.showInfo()); // Pizza: $10
You can create an object when you call the constructor function with the “new” keyword.
2. Defining Classes
In ES2015, you can define a class. It is not something quite new. Actually under the hood, the compiler creates a constructor function and establishes the prototype inheritance for you.
The previous code can be rewritten like this in ES2015. It is much easier to read.
class Product { constructor(n, p) { this.name = n; this.price = p; } showInfo() { return `${this.name}: \$${this.price}`; } } let product = new Product("Pizza", 10); console.log(product.showInfo()); // Pizza: $10
3. Constructors
A constructor is a special method to create and initialize the member fields. Only one method (with the name “constructor”) is allowed in a class.
4. Getters and Setters
JavaScript object does not have private members. You can access all internal fields and it is a bad thing.
class Product { constructor(n) { this.name = n; } } let product = new Product("Pizza"); console.log(product.name); // Pizza
As you can see, you can directly access the inner members.
But with proper convention, we can mitigate the problem.
- Prefix internal fields with the underscore ‘_‘
- Create a property with a getter and a setter
class Product { constructor(name) { this._name = name; } get name() { return this._name; } set name(value) { this._name = value; } } let product = new Product("Pizza"); // Possible but don't do it console.log(product._name); // do like this product.name = "Burger"; console.log(product.name);
The syntax is clear and easy to understand.