JavaScript Introducing ES2015 Classes Sub-Classes

Rifqi Fahmi
Rifqi Fahmi
23,164 Points

Does anyone notice that this new features seems like Java language ? hmmm

Just curious though hmmmmmmmmmm

4 Answers

Classes are just syntactic sugar. You can have a look at what Babel does with classes. There is some technical stuff added to the code but, in general, the following transformations are made:

  • Classes are translated to constructor functions
  • Methods are added to the prototype of the constructor
  • super is replaced by Person.call(this, name)
  • Student extends Person is replaced by the following:
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Tom Geraghty
Tom Geraghty
24,147 Points

Just to illustrate the great answers by others. Check out this repl/transpiler to see your code transformation in action: https://babeljs.io/repl/

Before:

class Student {
  constructor({ name, age, interestLevel = 5 } = {}) {
    this.name = name;
    this.age = age;
    this.interestLevel = interestLevel;
  }
} 

becomes:

"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Student = function Student() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      name = _ref.name,
      age = _ref.age,
      _ref$interestLevel = _ref.interestLevel,
      interestLevel = _ref$interestLevel === undefined ? 5 : _ref$interestLevel;

  _classCallCheck(this, Student);

  this.name = name;
  this.age = age;
  this.interestLevel = interestLevel;
};

I'd prefer to write the first over the second code block!

Charles-Antoine Francisco
Charles-Antoine Francisco
27,425 Points

Its true but like Guil said earlier, under the hood, JavaScript is still a prototype based language.

Benjamin Farnham
Benjamin Farnham
8,055 Points

I feel like all it is doing is simply trying to appeal to developers coming to learn JavaScript. Not a bad thing at all but for all practical uses, I find it not quite there yet.