Different approaches to adding properties using Javascript prototypes

When adding additional properties to a constructor, is it better to use constructorName.nameofProperty or constructorName.prototype.nameofProperty? And what are the differences between the two approaches?

Answer №1

Upon examining the console output of the code snippet below, you will notice that when something is added to an object's prototype it affects all instances of the constructor. In this case, both Jill and Tim now have a method called setAge, but only Jill has actually utilized it to set her age. Any additions made directly to the constructor do not get inherited by its instances.

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

var Tim = new Person("Tim", "Dawson");
var Jill = new Person("Jill", "Swanson");

Person.prototype.setAge = function(age) {
  this.age = age;
}

Jill.setAge(28);

Person.doesThisInherit = function() {
  console.log("No it doesn't");
}

var Sam = new Person("Sam", "Testy");

console.log(Tim);
console.log(Jill);
console.log(Sam);

Answer №2

It really comes down to what you're looking to achieve.

If you want the object created by the constructor function to have specific properties, then you'll need to add those properties directly to the object:

var constructorFunction = function () {
  this.someProperty = someValue;
}

Alternatively, if you're wanting to add properties to the constructor function itself, you can do so as follows:

constructorName.someProperty = someValue

However, it's important to note that this will only affect the function and not the objects created from it.

If you'd like all objects created with that function to share a common property without consuming extra memory, you can attach the property to the prototype. This way, each object will reference the same property through the prototype chain. On the other hand, if memory usage is not a concern, assigning individual properties to each object (as shown in the first example) may be more appropriate. This ensures that changes made to one object's property won't impact others created by the constructor function.

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

Using jQuery to define a variable with .attr method and subsequently modifying it

I am trying to work with multiple fields, some of which have corresponding labels: <input id="1" /><label for="1" /> <input id="2" /> <input id="3" /><label for="3" /> My goal is to retrieve the "for" attribute value from ea ...

Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here. My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql. I've managed to establish a connecti ...

Unable to expand child nodes using jstree open_node function

After loading my checkbox jstree, I want to automatically open the last accessed nodes (excluding select_node). Unfortunately, the open_node function seems to only work on the top-level parent nodes. I've attempted iterating through each node and call ...

What is preventing Facebook from merging its CSS/JS files together?

I wonder about the reasoning behind Facebook developers' decision not to consolidate their scripts and stylesheets into single files, opting instead to load them on demand through their CDN. Considering the complexity of Facebook as an application, I ...

Maintaining a reference list of HTML elements in a lengthy v-for loop can lead to performance issues

Task I am facing a challenge with a long list of elements in a v-for loop. My goal is to trigger the .focus() method on the next element when the user presses the "arrow-down" key. My Attempt <script setup> import { ref } from 'vue' const ...

execute the function based on the given ID

I've been attempting to dynamically add content using a function. My goal is for the content with the same anchor ID as the clicked anchor to be added, but it seems like nothing is happening. Is there a more effective approach to achieve this? $(&a ...

What is preventing me from modifying the data in a JSON object?

My task is to update the value "customer.signature", but I am facing an issue with my code. The JSON and HTML seem to be error-free, so the problem lies within my JS code. While "data.signature" updates correctly, "data.customer.signature" does not. The J ...

Is there a way to choose multiple dropdown items that share the same header?

Utilizing the Fluent UI React Northstar Dropdown component in my React project, I've encountered an issue with multiple item selection. It seems that when there are several items sharing the same header value, only one can be selected at a time. What ...

Ways to unzip binary information in node.js

Once I have decoded my data from base 64 to binary, my next step is to unzip this information. In my project, I am using node.js instead of PHP, which has a convenient gzdecode() function for decompressing data. However, with node.js, I am unsure of how t ...

Is it possible to adjust the points on a current path using Snap?

I have an SVG containing a path element: <path d="M54.7,0.8 L111.8,73.4 L79.9,126.1 L27.9,128.7 L0.5,74.2 L54.7,0.8 Z" id="Shape"></path> After exploring the meanings of SVG paths, I've learned that: M signifies moving to a point The L ...

Unable to permanently uninstall Node.js

I recently downloaded the forever package using the command: npm install forever -g However, when I attempted to uninstall it using: npm uninstall -g forever I received the message up to date in 0.042s Despite this, I am still able to access the forev ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

Having trouble getting the three.js EffectComposer to function properly

Seeking guidance on using EffectComposer for postprocessing renders, as my basic setup doesn't seem to be rendering anything on the screen. Any ideas on what I might be missing? <!doctype html> <html> <head> <title>game& ...

What is the best way to implement 2 conditions in the componentDidUpdate method?

Is there a way to include two conditions in an "if" statement within the componentDidUpdate method? Below is the code I am working with: componentDidUpdate(prevProps, prevState) { if ( prevState.address_id !== this.state.address_id && ...

Ways to expand the play and pause buttons and adjust the height of an HTML audio player

It's clear that the PLAY/PAUSE icons are smaller than intended, and the entire player is thinner than desired, making it difficult for some viewers to see. How can I enlarge the entire player? I have read that we do not have access to individual contr ...

Implementing the loading of a Struts 2 action with jquery in javascript

Looking to refresh a specific div using JavaScript with jQuery to target the div and a Struts action that loads the content. Can anyone offer advice on how to achieve this? The challenge lies in utilizing JavaScript and jQuery for this task. Best regards ...

Is it possible to verify if a bearer token has expired within an Angular application?

Is there a secure and efficient way to determine when a bearer token has expired in my Angular application? This is the issue I am facing: If I keep the app open in my browser, someone could potentially access sensitive information on my screen since I am ...

Adjusting the date to reflect the sender's timezone

Struggling with converting a UTC Date string with an offset to the user's local time accurately. When a date like 2017-06-21T20:26:28.744Z comes from our server, the goal is to turn it into a timestamp of the sender's local time, factoring in a 6 ...

Create a word filter that doesn't conceal the words

I have a code snippet that filters a JSON object based on name and title. I also have an array of specific words and I would like to modify the filter to highlight those words in the text without hiding them. $scope.arrayFilter=["bad,bill,mikle,awesome,mo ...

Extending the href value using jQuery at the end

Can someone help me with this link: <a id="Link" href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2745425453424b4b524940674e0a4355464e4909494253">[email protected]</a>?subject=I-Drain Bestellung& ...