3.3 KiB
3.3 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7dae367417b2b2512b79 | Extend Constructors to Receive Arguments | 1 | 扩展构造函数以接收参数 |
Description
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构造函数如此有用的一种方式。他们根据共享的特征和行为将对象组合在一起,并定义一个自动创建的蓝图。 Instructions
Dog
构造函数。这次,将其设置为采用参数name
和color
,并将属性numLegs
固定为4.然后创建一个保存在变量terrier
的新Dog
。将两个字符串作为name
和color
属性的参数传递给它。 Tests
tests:
- text: <code>Dog</code>应该收到<code>name</code>的论据。
testString: 'assert((new Dog("Clifford")).name === "Clifford", "<code>Dog</code> should receive an argument for <code>name</code>.");'
- text: <code>Dog</code>应该收到<code>color</code>的论据。
testString: 'assert((new Dog("Clifford", "yellow")).color === "yellow", "<code>Dog</code> should receive an argument for <code>color</code>.");'
- text: <code>Dog</code>应该将属性<code>numLegs</code>设置为4。
testString: 'assert((new Dog("Clifford")).numLegs === 4, "<code>Dog</code> should have property <code>numLegs</code> set to 4.");'
- text: 应该使用<code>Dog</code>构造函数创建<code>terrier</code> 。
testString: 'assert(terrier instanceof Dog, "<code>terrier</code> should be created using the <code>Dog</code> constructor.");'
Challenge Seed
function Dog() {
}
Solution
// solution required