DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  • Boosting React.js Development Productivity With Google Code Assist
  • Why Angular Performance Problems Are Often Backend Problems

Trending

  • Evolving Spring Boot APIs to an Event-Driven Mesh
  • Chaos Engineering Has a Blind Spot. Agentic AI Lives in It.
  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  • How to Write for DZone Publications: Trend Reports and Refcards
  1. DZone
  2. Coding
  3. JavaScript
  4. Two Problems of a JavaScript Class

Two Problems of a JavaScript Class

ECMAScript 6 saw the introduction of a 'class' keyword in JavaScript. We take a look at a couple gotchas you need to know about.

By 
Dhananjay Kumar user avatar
Dhananjay Kumar
·
Updated Jan. 02, 19 · Presentation
Likes (3)
Comment
Save
Tweet
Share
10.1K Views

Join the DZone community and get the full member experience.

Join For Free

Starting with ECMAScript 6, JavaScript has a class keyword for creating a class.There is no question that classes simplify the way objects are created, inheritance is implemented, etc. JavaScript classes have: 

  • Constructors 

  • Methods

  • Extends

The above features of a class help to easily write Object-Oriented JavaScript. As a developer, you do not need to know the complexities of prototype chains, relationships between function constructors and their prototype objects, and value of object's __proto__ properties, etc., to write effective Object-Oriented JavaScript. So, the class keyword is a good addition to the JavaScript language, however, it is not perfect. It has some problems, which may stop you from writing full-fledged Object-Oriented JavaScript. In this post, I am going to share two such problems.

No Static Member Properties in class

A static member property is shared by all object instances of the class. JavaScript class does not allow us to create static member properties inside a class.

You cannot declare properties directly in a class. You can only do so through the class's constructors, and the properties created inside the constructor are local to the object instances and not shared by all of them.

class Car {
    var a = 9; // unexpected indentifier error 
}

The above code will throw the error "unexpected identifier." There is a workaround to create a static property using the class prototype.

class Speaker {
    constructor(name) {
            Speaker.prototype.count++;
            this.name = name;
        }
    }
Speaker.prototype.count = 0; 

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

var a = new Speaker('dj');
var b = new Speaker('Jason');

console.log(a.count); // 2
console.log(b.count); // 2
console.log(a.count === b.count) // true 

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

Object Instances Do Not Copy Definitions From Class

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

function Speaker(name) {
    this.name = name;
    this.hello = function () {
        console.log('hey ' + this.name);
    }
}

Using the new operator, you can create object instances. 

var a = new Speaker('dj');
a.hello(); // hey dj 
var b = new Speaker('Jason');
b.hello(); // hey Jason

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

Speaker.prototype.hello = function () {
    console.log('Hello Speaker ' + this.name);
}

a.hello(); // hey dj 
b.hello(); // hey Jason 
a.__proto__.hello.call(a); // Hello Speaker DJ 

You are getting expected outputs while calling the hello method and to call the hello method of the Speaker prototype we use __proto__.

Now let us implement the above scenario using the class keyword.

class Speaker {

    constructor(name) {
        this.name = name;
    }
    hello() {
        console.log('hey ' + this.name);
    }
}

We have created the Speaker class with a constructor and an instance of the hello method. Let us create object instances of the Speaker class:

var a = new Speaker('dj');
a.hello(); // hey dj 
var b = new Speaker('Jason');
b.hello(); // hey Jason

So far, everything is as expected. Now go ahead and add the same function, hello, to the Speaker prototype.

Speaker.prototype.hello = function () {
    console.log('hello speaker  ' + this.name);
}

After adding the hello function to the Speaker prototype, call the hello function with object instances of Speaker.

a.hello(); // hello speaker dj 
b.hello(); // hello speaker jason 

You will find that the object instances a and b are now calling the hello function of the Speaker prototype instead of their own hello function.

This is happening because JavaScript classes are not like classes of real object-oriented languages. They do not create a copy of the class declaration in objects.

JavaScript

Published at DZone with permission of Dhananjay Kumar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  • Boosting React.js Development Productivity With Google Code Assist
  • Why Angular Performance Problems Are Often Backend Problems

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook