How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book:

function Car() {
   var self = this;
   self.type = "Car"
   self.go = function() {
      console.log("Going...");
   };
};

Toyota = function() { console.log("Original called"); };
Toyota.prototype = new Car();
Toyota.prototype.constructor = function() {
   var self = this;
   self.type = "Toyota";
   self.go = function() {
      console.log("A Toyota car is going...");
   }
};
Toyota.prototype.isJapaneseCar = true;

function TestCar() {
   console.log("Toyota.prototype.constructor: " + Toyota.prototype.constructor);
   var t = new Toyota();
   console.log("t.constructor: " + t.constructor);
   console.log(t.type);
};

The output in the Firefox console looked like this:

Toyota.prototype.constructor: function () {
   var self = this;
   self.type = "Toyota";
   self.go = function () {
      console.log("A Toyota car is going...");
   };
}
Original called
t.constructor: function () {
   var self = this;
   self.type = "Toyota";
   self.go = function () {
      console.log("A Toyota car is going...");
   };
}
Car

As seen from the output, the new Toyota() call:

var t = new Toyota();

did not run the Toyota.prototype.constructor function as expected, instead it still used the original function definition:

Toyota = function() { console.log("Original called"); };

A highly upvoted post provided detailed explanations and examples. It mentioned "3. It executes the constructor function, using the new object whenever this is mentioned." Does the term "constructor" refer to prototype.constructor? How are the following 3 lines related:

  1. Toyota = function() { console.log("Original called"); }
  2. Toyota.prototype.constructor = function() { ...
  3. var t = new Toyota();

[EDIT] My biggest confusion lies in why the constructor (Toyota.prototype.constructor) is not triggered when I invoke new Toyota()?

Answer №1

The constructor property within the prototype object is crucial as it holds a reference to the function responsible for creating instances of a particular type of object. I hope I am not adding confusion with this explanation.

In the case of a string object, you will find that the constructor property points to the String function (also known informally as the constructor).

console.log("".constructor); // This would display function String() { [native code] }

This is why it's common practice to realign the class (or the function) by assigning the constructor property back to itself.

Toyota.prototype.constructor = Toyota;

var t = new Toyota();
console.log(t.constructor); // outputs function Toyota() { /* definition */ }

I trust this provides clarity on your query.

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

Creating a div that becomes fixed at the top of the page after scrolling down a certain distance is a great way to improve user experience on a

I am struggling to create a fixed navigation bar that sticks to the top of the page after scrolling 500px, but without using position: fixed. Despite trying various solutions, none seem to work due to the unique layout of my navigation bar. Strangely enoug ...

The perfect approach for loading Cordova and Angularjs hybrid app flawlessly using external scripts

We have developed a single page hybrid app using cordova 3.4.0 and angularJS with the help of Hybrid app plugin(CPT2.0) in visual studio 2013. This app contains embedded resources such as jquery, angularjs, bootstrap, and some proprietary code. Additiona ...

Clicking on a specific month results in displaying only one row from the database rather than showing all rows associated with that particular month

I am facing an issue with my calendar feature on the website. The problem is that when I click on a specific month, it should display all the data associated with that particular month. However, the current code does not seem to work as expected. For insta ...

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

Is it possible to utilize dynamic imports in conjunction with a for loop in Next.js?

I often use dynamic import to bring in multiple components efficiently. Is it feasible to use a 'for' loop for this purpose? import dynamic from "next/dynamic"; let Dynamic = []; for (let i = 1; i < 80; i++) { const DynamicComponent = d ...

Issue with the positioning of bootstrap popover after content is added

Having trouble writing a function that adds a textarea to the bottom of a popover content when clicking on a button. The issue is that once the textarea is displayed, the popover extends downward and obscures the text. I'm looking for a solution where ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

The proper method for developing Vue components that are dependent on the parent build tools

In my experience, this issue might also arise in other frameworks with plugin/component ecosystems that rely on specific build tools (such as React components with JSX). While Vue serves as my use-case. Having developed numerous Vue components as single . ...

Flattening an array of Map in Typescript involves combining all the

I am working with an array containing entries of type Map<string, number> Is there a way to flatten this array into a single map? Map<string, number>[] converted to Map<string, number> Appreciate any help on this matter. ...

The integration of VueJS with Axios and the Google Maps API

Currently following [this][1] guide to develop a Google Map and now I am looking to execute a GET request with Axios: axios.get("http://localhost:8080/mapjson").then(function(response) { }) in order to integrate the information from my JSON file into the ...

How to clear input fields in Ant Design ReactJS components

Utilizing the form list component from antd in my react.js project https://ant.design/components/form/#Form.List I have a basic form list set up where I can easily add or remove fields. At times, I need to reset the form and remove any additional items t ...

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...

Determine in React whether a function returns a true value, and execute the code for false regardless

I have a hunch that this is related to the concept of asynchronicity. Essentially, I'm trying to validate whether a string (an answer to a question) already exists. If it does, the page should just show a message; otherwise, it should add the new que ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...

Issue: Attempting to write data after reaching the end in Node.js while using

I have encountered the following error: Heading Caught exception: Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15) at ServerResponse.res.write (/home/projectfolder/node_modules/express/node_modules/connect/lib/mid ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...