JS classes are not just simple syntactic sugar!

class first is good: private variables


Without class , is there any more elegant way to implement private variables of the following subclasses?
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
} // Person.constructor

getFullName() {
return this.firstName + " " + this.lastName;
}

} // Person
class Employee extends Person {

#salary;

constructor(firstName, lastName, salary) {
super(firstName, lastName);
this.salary = salary;
}

get salary() {
return this.#salary;
}

set salary(salary) {
this.#salary = salary;
console.log("Salary changed for " + this.fullName + " : $" + this.salary);
}

} // Employee

Imagine, we simulate (object) with the idea of ​​prototype chain:
const Person = {
set givenName(givenName) {
this._givenName = givenName;
},
set familyName(familyName) {
this._familyName = familyName;
},
get fullName() {
return `${this._givenName} ${this._familyName}`;
}
};

const test = Person; // This assumes that the class is simulated with an object
test.givenName = "Joe";
test.familyName = "Martinez";
console.log("test.fullName", test.fullName); // Joe Martinez
console.log("test.givenName", test.givenName); // undefined
console.log("test._givenName", test._givenName); // Joe

Private property _givenName is not implemented
On the other hand, a class can keep the value private, so that it cannot be modified outside the object:
For code examples, please refer to: javascript-classes-are-not-just-syntactic-sugar

class second best: super inheritance


class can be inherited and overridden more elegantly through super, for example:
class Cash {

constructor() {
this.total = 0;
}

add(amount) {
this.total += amount;
if (this.total < 0) this.total = 0;
}

} // Cash
class Nickles extends Cash {

add(amount) {
super.add(amount * 5);
}

} // Nickles

If it were the old-fashioned, prototype chain, it might look like this:
const Cash = function() {
this.total = 0;
}; // Cash
Cash.prototype = {
add : function(amount) {
this.total += amount;
if (this.total < 0) this.total = 0;
}

}; // Cash.prototype
const Nickles = function() {
Object.assign(this, new Cash());

this.add = function(amount) {
Cash.add.apply(this, amount);
};

} // Nickles

It's a bit messy to read, this is pointing back and forth, and there is an assign operation manually done in the constructor, which will increase the time consuming of code execution.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00