3.4 KiB
3.4 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7b8b367417b2b2512b53 | Use class Syntax to Define a Constructor Function | 1 | 301212 | Использовать синтаксис класса для определения функции конструктора |
Description
class
является просто синтаксисом, а не полноценной реализацией объектно-ориентированной парадигмы на основе классов, в отличие от языков, таких как Java, или Python, или Ruby и т. Д. В ES5 мы обычно определяем конструктор функции и используйте new
ключевое слово для создания экземпляра объекта. var SpaceShuttle = function (targetPlanet) {Синтаксис класса просто заменяет создание функции конструктора:
this.targetPlanet = targetPlanet;
}
var zeus = новый SpaceShuttle ('Юпитер');
класс SpaceShuttle {Обратите внимание, что ключевое слово
Конструктор (targetPlanet) {
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle («Юпитер»);
class
объявляет новую функцию и добавляется конструктор, который будет вызываться при вызове new
- для создания нового объекта.
Instructions
class
и напишите правильный конструктор, чтобы создать класс Vegetable
. Vegetable
позволяет вам создать объект-овощ с name
свойства, который будет передан конструктору.
Tests
tests:
- text: <code>Vegetable</code> should be a <code>class</code> with a defined <code>constructor</code> method.
testString: assert(typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function');
- text: <code>class</code> keyword should be used.
testString: assert(code.match(/class/g));
- text: <code>Vegetable</code> should be able to be instantiated.
testString: assert(() => {const a = new Vegetable("apple"); return typeof a === 'object';});
- text: <code>carrot.name</code> should return <code>carrot</code>.
testString: assert(carrot.name=='carrot');
Challenge Seed
/* Alter code below this line */
/* Alter code above this line */
const carrot = new Vegetable('carrot');
console.log(carrot.name); // => should be 'carrot'
Solution
class Vegetable {
constructor(name) {
this.name = name;
}
}
const carrot = new Vegetable('carrot');