Exploring Javascript: Understanding the Contrast Between Function and Class

In June 2015, with the introduction of ECMAScript 6, a new syntax for Javascript classes was unveiled.

The new syntax is exemplified by the following code snippet:

class Polygon {
      constructor(width, height) {
        this.width = width;
        this.height = height;
      }
}

This can be rewritten using traditional function syntax as follows:

function Polygon(width, height) {
    this.width = width;
    this.height = height;
}

So what advantages does using classes offer over traditional functions? And in what scenarios should one opt for classes instead of functions?

Answer №1

When comparing Class and Function in JavaScript, it's often said that Class is just syntax sugar. However, the distinction between the two does matter. The JS parser handles them differently by categorizing them into various AST nodes such as ClassDeclaration and ClassExpression, which are distinct node types in the resulting AST tree:

https://github.com/estree/estree/blob/master/es2015.md#classes

The introduction of new AST elements with the ES6 Classes spec like ClassBody, MethodDefinition, ClassDeclaration, ClassExpression, and MetaProperty signifies a shift in syntax:

  • ClassBody
  • MethodDefinition
  • ClassDeclaration
  • ClassExpression
  • MetaProperty

This variation in AST syntax can lead to different interpretations by the JavaScript engine when encountering Class or Function declarations.

The limitation lies in the fact that Class and Function declarations cannot be used interchangeably. This is evident when attempting to do something like:

class notWorking {
  return 1; // <-- creates a parser error
};

Herein lies a small problem - achieving private variables within Class declarations becomes more complex compared to using Function declarations:

function myClass() {
    var privateVar;
}

Unlike functions, only methods can be declared within the body of a Class declaration:

class myClass {
    var privateVar; // ERROR: should be a method
}

A proposed solution for creating private fields in the future involves syntax like:

class myClass {
   #privateVar; // maybe this works in the future?
}

Alternative approaches such as using Symbols for private properties have also been suggested:

Private properties in JavaScript ES6 classes

var property = Symbol(); 
class Something {
    constructor(){
        this[property] = "test";
    }
}

Further distinctions between classes and functions include issues like Hoisting and special keywords unique to each, such as constructor and super in Classes. These nuances contribute to a clearer expression of objects in an OOP manner through the ES6 Class syntax.

Additional differences, considerations, and limitations between classes and functions can be explored here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Answer №2

Class is essentially just a simplified way of creating classes in JavaScript, using functions underneath the surface. When you define a function as a class, the entire function serves as a constructor. If you want to add other member functions, you must do so within the constructor using this.something = .... For private members, you can use var something = ... (assuming no external injection). However, with a true class, the function is not automatically a constructor; you can explicitly separate it from other member functions and data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The node.js express framework is unable to fetch the URL and data from the node server

Attempting to create a basic application to retrieve data from a nodejs server. But encountering issues with accessing the file in both the browser and POSTMAN. Despite multiple attempts to verify the URLs, I have been unsuccessful. Below are the files i ...

To calculate the sum of input field rows that are filled in upon button click using predetermined values (HTML, CSS, JavaScript)

Greetings for exploring this content. I have been creating a survey that involves rows of buttons which, when clicked, populate input fields with ratings ranging from 5 to -5. The current code fills in one of two input fields located on opposite sides of ...

What is the best way to have the sidebar of a webpage slide out over the main body content that is being displayed?

Issue Summary I am experiencing an issue with the positioning of my sidebar, which is initially located 66% offscreen using -translate-x-2/3. The sidebar is meant to be pulled into view onmouseover, however, the main body content remains stuck in place. I ...

initiating an event within a modal controller

I have a $scope.$on callback function in my mainController. It works perfectly whenever I call it from each controller, but when I call it from a modalController after opening the modal, it doesn't work: define(['app', 'jquery'], ...

When developing a multi-page application using React, encountering the error "TypeError: Cannot read property 'pathname' of undefined" may indicate an issue

I am facing an issue while trying to develop a multi-page application using react-router. As I am new to React, I find it difficult to explain the problem clearly. My goal is to incorporate a login page into the application. Suggestions and alternative app ...

Shake up your background with a random twist

Seeking assistance with customizing the Aerial template from HTML5UP. I am interested in selecting a scrolling background randomly from a pool of images. Can someone guide me on how to achieve this? Presently, the background is defined within a code block ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

Utilizing React, generate buttons on the fly that trigger the display of their respective

Looking for a way to dynamically display 3 buttons, each of which opens a different modal? I'm struggling to figure out how to properly link the buttons to their respective modals. Here's the code I've attempted so far: Button - Modal Code: ...

Enhancing Element Generation and Data Association through jQuery

Currently, I am seeking a more streamlined approach to generate DOM alterations and update the object within .data(). At the moment, data is being supplied in an array of objects. I construct strings piecemeal, appending them to the table body, and affixi ...

What are some strategies for enhancing the efficiency of asynchronous data retrieval and caching?

I'm using this code to retrieve data asynchronously and store it in a cache for performance optimization: let cache = {} const optimizedFetch = async (url) => { if (url in cache) { // return cached result if available console.lo ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...

Creating dynamic form groups that allow for the addition and removal of forms while assigning unique identifiers and names to each input field

I am currently immersed in the development of a sophisticated CMS system. My main objective is to dynamically add and remove form inputs using JavaScript upon clicking a button, with the ultimate goal of submitting the data into a database via PHP script. ...

Is it possible to utilize Mouse hover to distinguish between various elements in React?

In an attempt to enhance this code, I wanted to make it so that when you hover over a specific element, another related element would also be displayed. Using useState in React seemed to be the most effective way to accomplish this after trying out a diffe ...

The combination of Three.js and React

Hello everyone! I am completely new to Three.js and I'm currently attempting to integrate it with React. While looking for resources, I came across this helpful medium article on the topic: Starting with React 16 and Three.js in 5 minutes My goal is ...

Adjusting speed dynamically within a setInterval function in JavaScript

I am working on a react application that requires displaying text with varying intervals between sentences, one at a time. To achieve this functionality, I stored all the sentences in an array and implemented a setInterval function: startShowingText() ...

Retrieving Blocked Images with Selenium: A Step-by-Step Guide

HTML: <html> <head> <body onload="document.getElementById('a').style.display='block';"> <div id="a" align="center" onclick="document.location.reload();" style="display: block; cursor: pointer;"> <img width="9 ...

Tips for creating a multitude of components

I have my react code in a single component and I am wondering how to split it into two components for the images container and showroom images. import React, { Component } from 'react'; export default class App extends Component { render() { ...

Large data sets may cause the Highchart Bar to not display properly

Currently, I am working on a web project that displays traffic usage in chart mode using Highchart Bar. The issue I am facing is that there are no errors thrown when running this code. <script type="text/javascript"> $(function () { $(&apos ...

Passing parameters in a jQuery function through a button click

I am trying to figure out how to pass the @item.Id value as a parameter in the click function for a button. Here is the code snippet: <button id="buttonEdit" style="color:darkgreen" data-toggle="modal" data-target="#Ed ...