Two Problems of a JavaScript Class

 

Starting ECMA 6, JavaScript has class keyword to create a class. I have written in detail about class here. There is no second question that class simplifies the way object is created, inheritance is implemented etc. JavaScript class has,

  • Constructors
  • Methods
  • Extends etc.

Above features of a class helps to easily write Object Oriented JavaScript. As a developer, you do not need to know complexities of prototype chains, relationship between function constructor and its prototype object, and value of object’s __proto__ properties etc. to write effective Object Oriented JavaScript.  So, class keyword  is good addition to JavaScript language, however it is not gospel perfect. It has some problems, which may restrict you to write full-fledged Object Oriented JavaScript. In this post, I am going to share two such problems. Read along,

No Static Member Properties in class

A static member property is shared by all object instance of the class. JavaScript class does not allow creating it inside the class.

You cannot declare properties directly in the class. You can only have it through class’s constructors, and properties created inside constructor is local to the object instances and not shared by all of them.

Above code will throw error “unexpected identifier”.  There is a work around to create static property using the class prototype.

Now on the instances of Speaker class, you can access static property count.

Therefore, you are able to create a static property, but not without help of understanding of prototype.  In my opinion class should have a way to create static property directly inside the class like a method or constructor.

Object instances does not copy definitions from class

To understand this problem, let us first revise Constructor Invocation Pattern and prototype chain. You have a function constructor Speaker.

Using new operator, you can create object instances,

In this approach, a and b object instances both have their own copy of hello method.  Now if you add a hello method to Speaker.prototype, still a and b object instances will access their own copy of hello method. Consider below code:

Read full article on the Infragistics blog

One thought on “Two Problems of a JavaScript Class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s