Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,174 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,426 Points

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

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.