--- id: 587d7dae367417b2b2512b79 title: Extend Constructors to Receive Arguments challengeType: 1 videoUrl: '' localeTitle: 扩展构造函数以接收参数 --- ## Description
最后一次挑战的BirdDog建设者运作良好。但是,请注意,所有的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构造函数如此有用的一种方式。他们根据共享的特征和行为将对象组合在一起,并定义一个自动创建的蓝图。
## Instructions
创建另一个Dog构造函数。这次,将其设置为采用参数namecolor ,并将属性numLegs固定为4.然后创建一个保存在变量terrier的新Dog 。将两个字符串作为namecolor属性的参数传递给它。
## Tests
```yml tests: - text: 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.");' ```
## Challenge Seed
```js function Dog() { } ```
## Solution
```js // solution required ```