0

Hey i'm just looking for a javascript explanation to explain why 'constructor called' is only called once as opposed to 5 times?

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 }
3
  • 3
    why do you think Dog is called 5 times? The instance that you've created is logged 5 times, but new Dog() is only called once, when you define obj. Commented Nov 16, 2020 at 22:35
  • is it because the new keyword is immediately executing the constructor function inside obj? Commented Nov 16, 2020 at 22:38
  • @Rez88 That is correct :o Commented Nov 16, 2020 at 22:40

1 Answer 1

1

You declare a property on your object named dog, the expression new Dog(...) is evaluated immediately. This is why you only see one log as the constructor is only called once.

This is a version that would call the constructor 5 times:

const obj = {
  // Notice the use of a function here. 
  dog: () => new Dog('roofus', 20)
}
for(let i = 0; i < 5; i++){
    // Call the function here.
    console.log(obj.dog())
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.