* 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>
2.4 KiB
2.4 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
587d7b8b367417b2b2512b53 | 使用 class 语法定义构造函数 | 1 | 301212 | use-class-syntax-to-define-a-constructor-function |
--description--
ES6 提供了一个新的创建对象的语法,使用关键字class
。
值得注意的是,class
只是一个语法糖,它并不像 Java、Python 或者 Ruby 这一类的语言一样,严格履行了面向对象的开发规范。
在 ES5 里面,我们通常会定义一个构造函数,然后使用 new
关键字来实例化一个对象:
var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
class
的语法只是简单地替换了构造函数的写法:
class SpaceShuttle {
constructor(targetPlanet) {
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
应该注意 class
关键字声明了一个函数,里面添加了一个构造器(constructor)。当调用 new
来创建一个新对象时构造器会被调用。
注意:
SpaceShuttle
。--instructions--
使用class
关键字,并写出正确的构造函数,来创建Vegetable
这个类:
Vegetable
这个类可以创建 vegetable 对象,这个对象拥有一个在构造函数中赋值的name
属性。
--hints--
Vegetable
应该是一个 class
,并在其中定义了constructor
方法。
assert(
typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function'
);
使用了class
关键字。
assert(code.match(/class/g));
Vegetable
可以被实例化。
assert(() => {
const a = new Vegetable('apple');
return typeof a === 'object';
});
carrot.name
应该返回 carrot
.
assert(carrot.name == 'carrot');
--seed--
--seed-contents--
// Only change code below this line
// Only change code above this line
const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'
--solutions--
class Vegetable {
constructor(name) {
this.name = name;
}
}
const carrot = new Vegetable('carrot');