freeCodeCamp/curriculum/challenges/japanese/02-javascript-algorithms-an.../es6/use-class-syntax-to-define-...

3.2 KiB

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 では、通常は constructor 関数を定義し、new キーワードを使用してオブジェクトをインスタンス化します。

var SpaceShuttle = function(targetPlanet){
  this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');

class 構文は、こうした constructor 関数による作成の代わりとなるだけです。

class SpaceShuttle {
  constructor(targetPlanet) {
    this.targetPlanet = targetPlanet;
  }
}
const zeus = new SpaceShuttle('Jupiter');

class キーワードによって、コンストラクターの追加先となる新しい関数を宣言していることに注意してください。 このコンストラクターは、新しいオブジェクトを作成するために new が呼び出されるときに呼び出されます。

注: ES6 のクラス名には、上記の SpaceShuttle のように「アッパーキャメルケース」を使用するのが慣例になっています。

constructor メソッドは、class を使用して作成されたオブジェクトを生成して初期化するための特別なメソッドです。 詳細については、「JavaScript アルゴリズムとデータ構造」認定講座の「オブジェクト指向プログラミング」のセクションを参照してください。

--instructions--

class キーワードを使用して constructor を記述し、Vegetable クラスを作成してください。

Vegetable クラスを使用すると、constructor に渡されたプロパティ name を持つ野菜オブジェクトを作成できます。

--hints--

Vegetable は、constructor メソッドが定義された class である必要があります。

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.namecarrot を返す必要があります。

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');