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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
  • Angular Apps Don’t Need Another Chatbot: Building Agentic UI Workflows With TypeScript
  • Text Analysis Without a Backend: Replacing an LLM Call With Intl.Segmenter and 60 Lines of JavaScript

Trending

  • The Twelve-Factor Agents: Building Production-Ready LLM Applications
  • Kill the Worker, Keep the Research: Build a Recoverable LangGraph Agent on Temporal
  • How to Format Articles for DZone
  • Building a Practical Cloud-Native Golden Path: A Guide to Kubernetes-Based Service Delivery, Self-Service, and Developer-Friendly Defaults

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Updated Jan. 02, 19 · Presentation
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
10.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
  • Angular Apps Don’t Need Another Chatbot: Building Agentic UI Workflows With TypeScript
  • Text Analysis Without a Backend: Replacing an LLM Call With Intl.Segmenter and 60 Lines of JavaScript

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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