JavaScript Class vs Function as Definition

Having trouble locating documentation for this issue. I devised a JavaScript class in the following manner:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  area = function() { 
    return this.height * this.width; 
  }
}

However, it failed to function properly on JSFiddle and I was advised to use this format:

var Polygon = function(height, width) {
  this.height = height;
  this.width = width;
  this.area =  function() { return this.height * this.width; }
}

I'm aware that there are multiple ways to achieve the same result. I am curious if this approach is similar to C++ where you can create a pointer like... Polygon *myPoly = new Polygon(3, 4); rather than Polygon myPoly(3, 4); or if it's purely stylistic. Additionally, any reasons as to why one method works on JSFiddle while the other does not would be appreciated.

Answer №1

The example you provided is not valid syntax. Here's the correct way to write it:

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

If you're using a browser that supports classes, this should work in JSFiddle. However, there are still some browsers that do not support classes.

There are multiple ways to achieve the same result in JavaScript due to its flexibility. The class syntax is relatively new and may not be fully supported in all widely-used browsers, such as Internet Explorer. Essentially, a class is just a more concise way of creating constructable objects compared to the traditional syntax shown in your second example.

In response to the C++ analogy, the two C++ code examples perform different tasks, while the JavaScript examples produce nearly identical results. To make the first example match the second example more closely, you could implement it like this:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
    this.area = function () { return this.height * this.width; };
  }
}

Alternatively, you could modify the second example to look like this:

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

Polygon.prototype.area = function() { return this.height * this.width; };

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

Is there a way to access the active request being processed in a node.js environment?

I am currently working with express.js and I have a requirement to log certain request data whenever someone attempts to log a message. To accomplish this, I aim to create a helper function as follows: function logMessage(level, message){ winston.log(le ...

The jQuery AJAX function appears to be unresponsive and failing to execute

I have a form that needs to update values on click of a radio button. Unfortunately, my jQuery skills are lacking. Here's what I have tried so far: HTML: <form> <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome"> ...

Performing a MongoDB query in a controller using the MEAN stack with Node.js

My goal with this controller is to retrieve all the results of a collection. Despite having one item in the prop collection, I am encountering an undefined error. Error: Cannot call method 'find' of undefined This snippet shows my server.js fil ...

Tips for managing and identifying canceled requests in an Angular HTTP interceptor

Having trouble handling cancelled requests in my http interceptor. Despite trying various methods from SO, I can't seem to catch it. Here is an example of how my interceptor looks: public intercept(req: HttpRequest<any>, next: HttpHandler) { ...

Change the class of each item in a list individually by hovering over them with the mouse using JavaScript

How to toggle classes in a list item one by one using the mouseover event in JavaScript? const items = document.querySelectorAll("ul li"); let currentItem; for (const item of items) { item.addEventListener("mouseover", e => { currentItem &am ...

How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. Whil ...

Issue with the scope causing global variable not to update when button is pressed

I am facing an issue with a declared variable and jQuery code that is supposed to store a form's value as the value of that variable when a button is clicked, and then execute a function. var verb = ""; $( "#submit" ).click(function() { verb = $(& ...

Choose the option for overseeing safaris

Hello there! I need some help with Safari. Can you please guide me on how to disable the arrows? https://i.stack.imgur.com/1gzat.png ...

Is there a way to completely remove an element from the dom once the ajax call has returned

I've been struggling to completely remove LI elements and their content, including the checkbox input, from the DOM without success. After an ajax callback, I am calling the following function, but it only removes the contents and not the element its ...

What is the best way to select an element based on its relationship to another Element object using a selector?

I am currently developing a small library in which I require the ability to select a relative element to the targeted element using the querySelector method. For instance: HTML <div class="target"></div> <div class="relative"></div& ...

The Ajax response fails to update my viewmodel

I have a value and a list that I need to update from within an Ajax callback. After retrieving a fresh value using .get(), I try to assign it to my view model's property, but the UI does not refresh properly. Below is the code snippet: function Searc ...

Transform a Javascript string variable into plain text within a pre-existing text document

Currently, I am storing user input from an HTML input as a JavaScript variable. The objective is to convert this data into plain text and save it in an existing text file. Essentially, each time the user provides input, it should be converted to plaintext ...

Challenge with the submission event listener

I am struggling to create my first event listener for the submit button that should respond to both a click and an enter key press. Currently, it is not working for either event, and I am unsure why. I do not intend to send any data to another page; I simp ...

Need two clicks for React setState() to update the user interface

As someone who is new to React, I've come across a common issue that many developers face. Despite trying various solutions, I still find myself having to click twice to update the UI state. The first click triggers the event handler but does not upda ...

best method for embedding javascript code within html (within a script tag)

In my quest to create dynamic HTML using jQuery and insert it into a specific div on my website, I encountered an issue. Specifically, I am attempting to generate an anchor element where both the href and label are determined by JavaScript variables. Here ...

Suspend features for moving between pages in history

In the application, we have two main pages - Home.vue and Statistics.vue. The Home.vue page renders the TableFields.vue component. On the Home page, there are fields with numbers that have an initial value of "3" set upon page load. An interval running a c ...

Node.js dynamically updates exports for efficient code execution

I am facing an issue with exporting and importing an object in my code. The object starts off empty but gets populated with keys and values when a button is clicked. However, when other files import this object, it still shows as empty. How can I dynamical ...

Identifying periods of inactivity using an embedded iframe

I have developed a website that showcases a three.js model within an iframe. My goal is to redirect users back to the homepage (index.html) after they have been inactive for a specified amount of time. While I have managed to achieve this using JavaScript, ...

The presence of ng-show dynamically adjusts the minimum height of a div element

I am encountering an issue with a div that has the class of wrapper. Inside this div, there is a parent div with the class of content-wrapper. The wrapper div includes a conditional directive ng-show which toggles between displaying or hiding its content. ...

Is there a way to redirect links within an iframe when a user decides to open them in a new tab?

I am currently developing a web application that allows users to access multiple services, such as Spark and others. When a user selects a service, like Spark for example, the app will open a new tab displaying my page (service.html) with user information ...