Rez88
Rez88

Reputation: 49

new constructors in javascript object methods

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 }

Upvotes: 0

Views: 32

Answers (1)

code-gorilla
code-gorilla

Reputation: 2418

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())
}

Upvotes: 1

Related Questions