Class is not just a Syntactic sugar in Javascript

The “class” syntax in Javascript

class example{
constructor() { this.i=10; }
method1() { var i=0;}
method2() { console.log()}
}

Sometimes people say that class is a “syntax sugar” (syntax that is designed to make things easier to read, but doesn’t introduce anything new) in JavaScript, because we could actually declare the same without class keyword at all:

function User(name) {
this.name = name;
}

User.prototype.sayHi = function() {
alert(this.name);
};

let user = new User("John");
user.sayHi();

The result of this definition is about the same. So, there are indeed reasons why class can be considered a syntax sugar to define a constructor together with its prototype methods.

Although, there are important differences.

  1. First, a function created by class is labeled by a special internal property [[FunctionKind]]:"classConstructor". So it’s not entirely the same as creating it manually.
  2. Unlike a regular function, a class constructor can’t be called without new:
class User {
constructor() {}
}

alert(typeof User); // function
User(); // Error: Class constructor User cannot be invoked without 'new'

3. Class methods are non-enumerable. A class definition sets enumerable flag to false for all methods in the "prototype".That’s good, because if we for..in over an object, we usually don’t want its class methods.

4. Classes always use strict. All code inside the class construct is automatically in strict mode.

Suffering from Knowledge Quest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store