JavaScript object methods have recently been updated with fresh constructors

I'm curious to understand why the 'constructor called' message is only displayed once instead of five times in this JavaScript example.

const Dog = function(name, age){
  this.name = name; 
  this.age = age; 
  console.log('constructor called'); 
}
const obj = { 
  dog: new Dog('roofus', 20)
}
const main = ()=>{
  for(let i = 0; i < 5; i++){
    console.log(obj.dog)
  }
}
main();
'constructor called'
Dog { name: 'roofus', age: 20 }
Dog { name: 'roofus', age: 20 }
Dog { name: 'roofus', age: 20 }
Dog { name: 'roofus', age: 20 }
Dog { name: 'roofus', age: 20 }

Answer №1

If you define a property on your object called dog, the code new Dog(...) will be executed immediately. This is why there is only one log, since the constructor is only invoked once.

To see the constructor being called 5 times, you can use this version:

const obj = {
  // Using a function as the value for 'dog' property.
  dog: () => new Dog('roofus', 20)
}
for(let i = 0; i < 5; i++){
    // Invoke the function here to call the constructor.
    console.log(obj.dog())
}

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

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

Is it possible to pass hooks as a property value from a useEffect in React.js?

As a newcomer to React, I am struggling to grasp the concept of how to use useEffect effectively. In one of my components, I have an array of objects stored in a file named cardData.js. These objects are used to automatically create cards, each containing ...

Knockout.JS encounters difficulty retrieving the value attribute in a select tag when the data is sourced from the server

After making an ajax request and binding the dropdown list, I noticed that the select tag was not reading the value attribute. However, when I bind the drop down list in the view model, it does recognize the value. For example: It works if I bind the mode ...

The value is currently unset in the TypeScript language

The variable `this.engenes_comparte` is showing up as undefined inside the subscribe function, but it works fine outside of it. baja(){ this._restService.getEngines(this._globalService.currentFisherMan.nid).subscribe((data : any[]) => { le ...

Experiencing difficulties establishing a connection between the React client and Node.js server using SocketIO

I am currently getting familiar with socketIO and have successfully set up a basic nodejs server. However, I am facing an issue where my nextJS app is unable to connect to the server as expected. Despite no errors being displayed, the messages that should ...

Employing jQuery to attach a new div to a dynamically generated div following a successful AJAX request

Currently, I am utilizing the marvelous WP-Polls plugin for WordPress, which boasts an innovative AJAX polling system. My main objective is to append a hidden div (.comment-block) to a fresh div (.voted) that will be dynamically injected into the DOM by th ...

The iframe is displaying a MIME warning for pdfmake: Resource being interpreted as a Document but transferred with MIME type application/pdf

We are developing a single-page application using Vue.js. Our goal is to generate a PDF on the client side, and we have chosen pdfMake from npm for this purpose. As per the documentation, to display the generated PDF within an <iframe>, you can simp ...

In JavaScript, use regular expressions to replace every instance of a link with its corresponding href object (map link -> a href=link)

I am looking to replace the following text: "wjjghwkjghwkjgh https://www.google.com jhgkwjhgkwhgk https://youtube.com" with: "wjjghwkjghwkjgh <a href='https://www.google.com'>https://www.google.com</a> jhgkwjhgkwhgk <a href=&a ...

Click to refine list or view

Currently, I am engaged in creating my own version of a social media platform inspired by Twitter. In this project, tweets are being automatically generated from a JavaScript file. One key feature I'm working on is that when a user clicks on a usern ...

Struggling with displaying MySQL data in JSON format using Highcharts

Currently, I am attempting to display data from a PHP file on an area graph by using the example found here. Initially, all the data was commented out before being passed to the array. Now, my focus is solely on displaying one portion of the data. I suspec ...

Modifying button styles in Angular UI Datepicker

In this plunk, there is an Angular UI Datepicker with a template. I'm trying to customize the colors of the "Today", "Clear", and "Close" buttons by editing the popup.html. However, even after changing the classes in the code, the datepicker still sho ...

AngularJS Component enthusiasts

While going through a tutorial on the Angular UI Router GitHub page (link: https://github.com/angular-ui/ui-router), I came across an intriguing code snippet: var myApp = angular.module('myApp', ['ui.router']); // For Component users, ...

Sending Paypal IPN Data to Node.JS: A Step-by-Step Guide

I'm looking to implement a real-time donation system on my website that can update all users simultaneously. The challenge I'm facing is that the IPN (Instant Payment Notification) page, responsible for verifying payments, is written in PHP. Unf ...

Just discovered a background change triggered by the time, but unable to replicate it

I find it odd that everything works perfectly fine with document.body.style.background, yet I can't seem to change the style of this particular div. Here is the code snippet: var container = document.getElementById("container"); var updateTime = fu ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

Ways to identify when a jQuery ajax request has finished executing?

Currently, I have a dropdown menu of countries that is populated using a jQuery ajax call. The issue I am facing is determining when the call is complete so that I can correctly select a country afterwards. Any function I call after the ajax function is tr ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...

Does the Array Splice method always remove an item from the end?

I'm having trouble with deleting an item from an array using Array.splice. It seems to always delete the item from the end instead of where I want it to be removed. I'm working with Vue.js and dynamically adding items to an array, but when I try ...

Which method is better for opening a new window - using window.open or adding an onclick

In the process of developing a Next.js application for users to download software, each software has its own unique download link. In order to achieve this functionality, I need to accomplish two specific tasks when a user clicks on the download link: Ope ...

Utilizing .show() and .hide() in conjunction with the opener

I have a website with a few photos, and when a user clicks on a photo, a div opens up to display an album, similar to Facebook's photo viewer. I want to be able to press the ESC key to go back to the original page. Inside the showAlbumDiv div, an ifr ...