Files
freeCodeCamp/curriculum/challenges/japanese/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md
freeCodeCamp's Camper Bot e6b05ee25d chore(i18n,learn): processed translations (#54537)
Co-authored-by: Naomi <nhcarrigan@gmail.com>
2024-04-26 12:26:37 +07:00

3.3 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 キーワードを使用してオブジェクトを作成する新しい構文が提供されています。

ES5 では、constructor 関数を定義して、new キーワードを使ってオブジェクトをインスタンス化することによってオブジェクトを作成できました。

ES6 では、class 宣言が new キーワードにより呼び出される constructor メソッドを持ちます。 constructor メソッドが明示的に定義されない場合は、暗黙的に引数なしで定義されます。

// Explicit constructor
class SpaceShuttle {
  constructor(targetPlanet) {
    this.targetPlanet = targetPlanet;
  }
  takeOff() {
    console.log("To " + this.targetPlanet + "!");
  }
}

// Implicit constructor 
class Rocket {
  launch() {
    console.log("To the moon!");
  }
}

const zeus = new SpaceShuttle('Jupiter');
// prints To Jupiter! in console
zeus.takeOff();

const atlas = new Rocket();
// prints To the moon! in console
atlas.launch();

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(__helpers.removeJSComments(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');