Search code examples
javascriptobjectmethodsconstructornew-operator

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 }

Solution

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