Ive创建了一个名为Cat的构造函数。 var fluffy是该实例。

香港专业教育学院试图设置一个默认值的品种是虎斑。但是,当我注销时,蓬松的品种是不确定的。

'use strict';

function Cat(name, age, breed) {
  this.name = name,
  this.age = age,
  this.breed = breed
}

Cat.prototype.breed = "tabby";

var fluffy = new Cat ("Fluffy the 3rd", "4 years");

console.log(fluffy);


控制台结果:

Object { name: "Fluffy the 3rd", age: "4 years", breed: undefined }

最佳答案

这是因为您尚未将值传递给breed参数,因此它将使用Cat.prototype.breed = 'tabby'参数值this.breed =覆盖undefined

也许您想这样做:



'use strict';

function Cat(name, age, breed) {
  this.name = name; this.age = age;
  if(breed || breed === 0)this.breed = breed;
}

Cat.prototype.breed = 'tabby';

var fluffy = new Cat('Fluffy the 3rd', '4 years');

console.log(fluffy);

09-27 04:56