Files
2022-01-20 20:30:18 +01:00

2.1 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7dad367417b2b2512b78 コンストラクターを使用してオブジェクトを作成する 1 18233 use-a-constructor-to-create-objects

--description--

次に示すのは前回のチャレンジで取り上げた Bird コンストラクターです。

function Bird() {
  this.name = "Albert";
  this.color  = "blue";
  this.numLegs = 2;
}

let blueBird = new Bird();

注: コンストラクター内の this は、作成されるオブジェクトを常に参照します。

コンストラクターを呼び出すときに new 演算子を使用していることに注目してください。 これにより、blueBird という Bird の新しいインスタンスを作成するように JavaScript に伝えます。 new 演算子がなければ、コンストラクター内の this は新しく作成されたオブジェクトを指さず、予期せぬ結果をもたらします。 これで blueBird は、Bird コンストラクター内で定義されているすべてのプロパティを持ちます。

blueBird.name;
blueBird.color;
blueBird.numLegs;

他のオブジェクトと同様に、プロパティにアクセスして変更することができます。

blueBird.name = 'Elvira';
blueBird.name;

--instructions--

前のレッスンの Dog コンストラクターを使用して、Dog の新しいインスタンスを作成し、それを変数 hound に割り当ててください。

--hints--

houndDog コンストラクターを使用して作成する必要があります。

assert(hound instanceof Dog);

Dog のインスタンスを作成するには、new 演算子を使用する必要があります。

assert(code.match(/new/g));

--seed--

--seed-contents--

function Dog() {
  this.name = "Rupert";
  this.color = "brown";
  this.numLegs = 4;
}
// Only change code below this line

--solutions--

function Dog() {
  this.name = "Rupert";
  this.color = "brown";
  this.numLegs = 4;
}
const hound = new Dog();