The prototype property in Javascript is being overridden

I'm feeling a bit puzzled by the inner workings of Javascript prototyping. Here is an example code snippet that I have:

function Person () {
  this.name = "no name";
  this.setName = function (n) {
    this.name = n;
  }
}

function Student () {
  this.id = "123";
}
Student.prototype = new Person();

s = new Student();
s.setName("Klaus");

Upon running this code, the object s ends up with two names. It has the name "Klaus" set in the object itself and the default "no name" from its prototype. While I understand that it's due to property shadowing and technically works correctly, it just doesn't sit right with me. Is there a more natural way to make use of only the property from the prototype?

Answer №1

If you wish to modify the prototype property directly, it is possible but may require a significant amount of effort and is not usually recommended practice. A better approach would be to call the Person constructor within the correct this context.

It is strongly advised to utilize Object.create instead of the new Operator when assigning to the function's prototype property. Using the new Operator can cause the Person constructor to be called in the incorrect this context. To avoid this issue, you can establish a link like this:

Student.prototype = Object.create(Person.prototype);

If you prefer to invoke the parent constructor (Person) within Student, you can do so by using call in the constructor with the appropriate this context:

function Student() {
  Person.call(this);
  this.id = "123";
}

In addition, to prevent creating a separate function for each instance, consider moving the setName function to the [[Prototype]] of Person:

function Person() {
  this.name = "no name";
}

Person.prototype.setName = function(n) {
  this.name = n;
}

function Student() {
  Person.call(this); // Call the Person constructor
  this.id = "123";
}
Student.prototype = Object.create(Person.prototype);

s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'

Alternatively, as mentioned by @Teemu, you could also define the name property on the Person.prototype to serve as a default value:

function Person() {
}

Person.prototype.setName = function(n) {
  this.name = n;
}

Person.prototype.name = "no name"; // Define the name directly

function Student() {
  Person.call(this); // only necessary if other operations are required from the Person constructor
  this.id = "123";
}
Student.prototype = Object.create(Person.prototype);

s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'

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

Passing Parameters to Razor Pages Controller

Within my controller, there exists a function as follows: public ActionResult AddSubSub(int? idOfSubsub) { return RedirectToAction("Index", new { searchword = "" }); } I am able to invoke this function without providing any parameter. I attempted the ...

What is the best way to create a line break in a flex div container to ensure that overflowing items wrap onto the next line using

Using material-ui popper to display a list of avatars. Trying to arrange the avatars horizontally within the popper. <Popper style={{ display: 'flex', maxWidth: '200px', }}> <div style={{ marginRight: '20px' }}&g ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

Retrieve the key associated with the value array that contains the text being searched for in an AJAX

I have a project where I am handling data to develop a search tool that allows users to search for the name of an individual involved in a legal case. The tool will then display a table with the individual's name, role, and other case details in a spe ...

Submitting several individual files through distinct Dropzones within a single form

I have implemented a form that allows users to add multiple rows, each containing name and avatar fields. My goal is to utilize Dropzone.js in order to create individual droppable areas for each avatar field. Every time a new row is added, a new Dropzone ...

What is the process for converting variables from browser script to Python code?

I ran the script below in my browser webdriver.execute_script("document.getElementsByClassName('bulk_item').length") My goal is to have the number that the script returns stored in a variable called elem for easy access. However, simp ...

Guide to utilizing an Ajax response object

Here is the code I am using to display data based on values selected from dropdowns: $("#botao-filtrar").click(function(){ $(".mask-loading").fadeToggle(1000); $.ajax({ url: 'datacenter/functions/filtraDashboardGeral.php', as ...

Can you explain the distinction between compiled and interpreted programming languages?

Despite my efforts to research the topic, I am still confused about the distinction between a compiled language and an interpreted language. It has been mentioned that this is one of the distinguishing factors between Java and JavaScript. Can someone ple ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Displaying both items upon clicking

Hey there, I'm having an issue where clicking on one article link opens both! <span class='pres'><img src='http://files.appcheck.se/icons/minecraft.png' /></span><span class='info'><a href=&apo ...

I often find myself frustrated while using Next.js because the console automatically clears itself, making it difficult for me

I am facing an issue with my form in the Next.js app. Here is how it is defined: <form onSubmit = { async() => await getCertificate(id) .then(resp => resp.json()) .then(data => console.log(data)) }> Whenever there is an erro ...

Is there a way to prevent javascript from automatically inserting tags when selecting text?

If you want to view the Fiddle Here Essentially, it's a text-highlighting tool that works almost flawlessly. The problem arises when it encounters tags like <p> or <br> within the selection. The JavaScript code seems to automatically in ...

Attempting to implement ajax for form submission, however finding that the $_POST array is coming back as empty

I'm attempting to send JavaScript arrays to a new page using Ajax. Although there are numerous questions on this topic on Stack Overflow, I have decided to implement Ajax in the following manner after examining various answers: var test = {}; test[& ...

Retrieve information transmitted from Angularjs through a multipart POST request to Nodejs and save it to a file

I am currently struggling with a challenging issue regarding uploading files from a web browser using angular js for the front end. After clicking send, the data is routed to a Nodejs express server, but unfortunately I am unable to retrieve my data. My m ...

Is it necessary for me to be familiar with AngularJS in order to redesign an app for Angular 2+

I'm curious - when rewriting an application from AngularJS to Angular 2+, do you need to be familiar with both, or is knowing just Angular 2+ sufficient? ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

Angular JS allows you to easily remove the # symbol from a URL, improving the

I am encountering a problem with the "#" symbol in my angular js website's URL. I need to remove the # from the URL but the method provided isn't working and the site is not displaying properly. Can someone advise me on how to successfully remove ...

Can a library be developed that works with both Java and JavaScript/TypeScript?

I specialize in Angular development. Our front- and backend both contain specialized calculation methods that work like magic. Although the classes are the same, any bugs found in the calculations have to be fixed separately in two different projects. Is ...

Locating items within a complex array and identifying their corresponding positions

I recently found an interesting code snippet from a different question that allowed me to identify an object. However, I am now faced with the challenge of determining the position of that object within the array. Let's take a look at the example belo ...

Having trouble reaching the AngularJS animation class breakpoint for removeClass or addClass operations

Can anyone help me figure out why my animation class isn't triggering in this codepen? I can access the controller methods fine, but the animation class doesn't seem to work properly. Any ideas on what I might be missing? Check out the codepen w ...