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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Dhananjay Kumar user avatar by
Dhananjay Kumar
·
Jan. 02, 19 · Presentation
Like (3)
Save
Tweet
Share
9.25K 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. I have written in detail about classes here.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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • NoSQL vs SQL: What, Where, and How
  • The Power of Docker Images: A Comprehensive Guide to Building From Scratch
  • How Chat GPT-3 Changed the Life of Young DevOps Engineers
  • Asynchronous Messaging Service

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: