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

The column must have a defined value and cannot be left empty

I encountered an issue while trying to populate a database with seed data. The error message I received is: name: 'SequelizeDatabaseError', parent: Error: Column 'id' cannot be null code: 'ER_BAD_NULL_ERROR', errno: 1048, sql ...

Can a variable containing HTML code be iterated through with a loop?

I am currently working on setting up a select button that will receive options from an ajax call. The ajax call is functioning properly. However, I am facing a challenge when trying to create a variable containing the HTML. I am unsure of how to iterate a ...

Is there a way to generate a hierarchical list menu using strings?

Within an HTML Application (HTA), I am utilizing vbscript to retrieve a list of subnet locations which is output as text in the following format: Chicago Denver Dallas Dallas/North Dallas/South Dallas/West Dallas/West/Building1 Dallas/West/Bu ...

Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS fun ...

What is the best way to limit a slash command to only be accessible to those with specific roles on a Discord server?

I am currently working on a discord bot using Discord.js V14 and implementing a command called "claimticket". However, I am facing an issue where I need to restrict this command to only members who possess one of the two specific roles that I have mentione ...

What is the best way to run a callback once several Ajax requests have finished?

I am facing a challenge with executing a callback function after multiple jQuery Ajax requests have been completed. The issue arises when these Ajax requests call another function, resulting in the functions being undefined. I suspect that the root of ...

What is the best way to store an ES6 Map in local storage or another location for later use?

let map = new Map([[ 'a', 1 ]]); map.get('a') // 1 let storageData = JSON.stringify(map); // Saving in localStorage. // Later: let restoredMap = JSON.parse(storageData); restoredMap.get('a') // TypeError: undefined is not a ...

Is it possible to notify the user directly from the route or middleware?

In my current setup, I am utilizing a route to verify the validity of a token. If the token is invalid, I redirect the user to the login page. I am considering two options for notifying users when they are being logged out: either through an alert message ...

The jQuery toggle functionality seems to be malfunctioning

I have created a form that should toggle (hide and show) with the click of a button, but for some reason it's not working. Can someone please take a look at my code below and let me know what I'm doing wrong? $(document).ready(function () { ...

Is the key to achieving optimal client interactions within a client layout, while still maintaining its role as a server component, truly possible?

My current challenge involves managing modals opening and closing with server components instead of client components. In the past, I used to lift the state up to my Layout for client components: export default function Layout({ children }) { const [showP ...

Navigating smoothly through different URLs to a single state using Angular's UI-Router

I recently started using angular's ui-router and I am looking for a way to configure multiple URLs to point to the same state. For instance: /orgs/12354/overview // should show the same content as /org/overview Currently, my $state provider is set u ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

Can Authorization be Combined with Filtering in a Node.js RESTful API?

In my current setup, I have a web application communicating with a RESTful API to interact with the database. The frontend of the web app uses Angular HTTP to post/get/put data to the backend, which then manages authentication, interacts with the API, and ...

Can you explain the purpose and function of stub.callsArg(index) feature in Sinon.JS?

Confusion has set in as I try to make sense of this. According to the documentation: stub.callsArg(index) - This command prompts the stub to execute the callback function found at the specified index. For instance, using stub.callsArg(0); will trigger the ...

Instructions for removing a single key value pair from every object in an array and transferring it to a designated object within the same array

I need to update an array of objects by adding a key and value (e.g., age:15) to an object with the name email, while removing the age property from other objects in the array. [ { name: 'test', lname: 'last', age: 5 }, ...

What is the best way to toggle the visibility of a dynamically created HTML element in ASP.NET?

I'm working on a program that displays two different prices depending on whether the user is registered or not. Registered users will see both the normal price and the discounted price, while unregistered users will only see the normal price. I need t ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Adjusting the height of the Sencha Touch container to accommodate its content

In Sencha Touch, I have a view that generates a popup box from the right when a button in the bottom toolbar is clicked: Ext.define('TheApp.view.PopupTablet',{ extend: 'Ext.form.Panel', xtype: 'popupbox', confi ...

Improving the innerHTML syntax

I am looking for the correct syntax to add content to an element using innerHTML. Here is an example that isn't working as expected: openNewWindow: function(content) { popupWin = window.open(content, 'open_window', 'menubar, ...

Transmit information from an HTML input field (not a form) to a Python CGI script through AJAX

I am currently facing a challenge where I need to send data programmatically without using form fields directly to a python CGI script. The issue lies in not knowing how to extract this data in Python. Normally, with a form, I could use "form = cgi.FieldSt ...