javascript 对象方法中的新构造函数
new constructors in javascript object methods
嘿,我只是在寻找 javascript 解释来解释为什么 'constructor called' 只被调用一次而不是 5 次?
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 }
您在名为 dog
的对象上声明了一个 属性,表达式 new Dog(...)
会立即被计算。这就是为什么你只看到一个日志,因为构造函数只被调用一次。
这是一个会调用构造函数 5 次的版本:
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())
}
嘿,我只是在寻找 javascript 解释来解释为什么 'constructor called' 只被调用一次而不是 5 次?
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 }
您在名为 dog
的对象上声明了一个 属性,表达式 new Dog(...)
会立即被计算。这就是为什么你只看到一个日志,因为构造函数只被调用一次。
这是一个会调用构造函数 5 次的版本:
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())
}