* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
1.8 KiB
1.8 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
587d7dad367417b2b2512b78 | 使用构造函数创建对象 | 1 | 18233 | use-a-constructor-to-create-objects |
--description--
在上一个挑战中,我们用所学到的知识创建了一个Bird
构造函数:
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
// 构造器内的 "this" 一直指向创建的对象
}
let blueBird = new Bird();
注意:通过构造函数创建对象的时候要使用new
操作符。因为只有这样,JavaScript 才知道要给Bird
这个构造函数创建一个新的实例
:blueBird
。如果不使用new
操作符来新建对象,那么构造函数里面的this
就无法指向新创建的这个对象实例,从而产生不可预见的错误。 现在blueBird
这个实例就继承了Bird
这个构造函数的所有属性,如下:
blueBird.name; // => Albert
blueBird.color; // => blue
blueBird.numLegs; // => 2
由构造函数创建的实例也和其他对象一样,它的属性可以被访问和修改:
blueBird.name = 'Elvira';
blueBird.name; // => Elvira
--instructions--
使用上一个课时中的Dog
构造函数创建一个Dog
的新实例,并把它赋值给变量hound
。
--hints--
hound
应该是通过Dog
构造函数来创建的。
assert(hound instanceof Dog);
你的代码中应该使用new
操作符来创建Dog
构造函数的新实例
。
assert(code.match(/new/g));
--seed--
--seed-contents--
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
// Only change code below this line
--solutions--
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
const hound = new Dog();