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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack
  • Overcoming React Development Hurdles: A Guide for Developers

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Beyond Microservices: The Emerging Post-Monolith Architecture for 2025
  • Overcoming React Development Hurdles: A Guide for Developers
  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  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
9.9K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack
  • Overcoming React Development Hurdles: A Guide for Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!