freeCodeCamp/curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.russian.md

3.4 KiB
Raw Blame History

id, title, challengeType, forumTopicId, localeTitle
id title challengeType forumTopicId localeTitle
587d7b8b367417b2b2512b53 Use class Syntax to Define a Constructor Function 1 301212 Использовать синтаксис класса для определения функции конструктора

Description

ES6 предоставляет новый синтаксис для создания объектов с использованием класса ключевых слов. Следует отметить, что синтаксис 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');