N-OMS Tech Radar

This publication focuses on cloud technologies, application development, software architectures…

Follow publication

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.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in N-OMS Tech Radar

This publication focuses on cloud technologies, application development, software architectures, best practices, the latest advancements in web technologies, and best engineering practices.

Responses (1)

Write a response

For me, JS classes really *clicked* when I started using Chat GPT. Previously, my own code was simple enough and I could get away without employing any real structure, so long as my chaos code returned the answer I was happy. However, AI certainly…