Bird
和Dog
建设者运作良好。但是,请注意,所有的Birds
与该创建Bird
构造自动命名伟业,颜色为蓝色,有两条腿。如果您希望鸟类的名称和颜色具有不同的值,该怎么办?可以手动更改每只鸟的属性,但这将是很多工作: 让swan = new Bird();假设您正在编写一个程序来跟踪鸟舍中数百甚至数千种不同的鸟类。创建所有鸟类需要花费大量时间,然后将每个属性的属性更改为不同的值。为了更轻松地创建不同的
swan.name =“卡洛斯”;
swan.color =“white”;
Bird
对象,您可以设计Bird构造函数来接受参数: function Bird(名称,颜色){然后传入值作为参数,将每个独特的鸟定义到
this.name = name;
this.color = color;
this.numLegs = 2;
}
Bird
构造函数中: let cardinal = new Bird("Bruce", "red");
这给出了一个Bird
的新实例,其名称和颜色属性分别设置为Bruce和red。 numLegs
属性仍设置为2. cardinal
具有以下属性: cardinal.name // =>布鲁斯构造函数更灵活。现在可以在创建时为每个
cardinal.color // =>红色
cardinal.numLegs // => 2
Bird
定义属性,这是JavaScript构造函数如此有用的一种方式。他们根据共享的特征和行为将对象组合在一起,并定义一个自动创建的蓝图。 Dog
构造函数。这次,将其设置为采用参数name
和color
,并将属性numLegs
固定为4.然后创建一个保存在变量terrier
的新Dog
。将两个字符串作为name
和color
属性的参数传递给它。 Dog
应该收到name
的论据。
testString: 'assert((new Dog("Clifford")).name === "Clifford", "Dog
should receive an argument for name
.");'
- text: Dog
应该收到color
的论据。
testString: 'assert((new Dog("Clifford", "yellow")).color === "yellow", "Dog
should receive an argument for color
.");'
- text: Dog
应该将属性numLegs
设置为4。
testString: 'assert((new Dog("Clifford")).numLegs === 4, "Dog
should have property numLegs
set to 4.");'
- text: 应该使用Dog
构造函数创建terrier
。
testString: 'assert(terrier instanceof Dog, "terrier
should be created using the Dog
constructor.");'
```