0

以下のコードを使用して、choc の値とタイプを出力しようとしていますが、チョコレートのタイプとミルクが undefined になっています。誰かがタイプを出力する方法を理解するのを手伝ってもらえますか? 私はしばらくこれに取り組んできましたが、クリックしていません。ありがとう!

// we set up a base class
function Candy() {
    this.sweet = true;
}

// create a "Chocolate" class with a "type" argument
Chocolate = function(type){
    this.type = type;
};

// say that Chocolate inherits from Candy

Chocolate.prototype = new Candy();

// create a "choc" object using the Chocolate constructor 
// that has a "type" of "milk"

var choc = new Object();
choc.type = "milk";

// print the sweet and type properties of choc
console.log(choc.sweet);
console.log(choc.type);

//////これは私が変更したものであり、まだ機能しません//////////

// we set up a base class
function Candy() {
    this.sweet = true;
}

// create a "Chocolate" class with a "type" argument
Chocolate = function(type){
    this.type = type;
};

// say that Chocolate inherits from Candy

Chocolate.prototype = new Candy();

// create a "choc" object using the Chocolate constructor 
// that has a "type" of "milk"

var choc = new Chocolate();
choc.type = "milk";

// print the sweet and type properties of choc
console.log(choc.sweet);
console.log(choc.type);
4

1 に答える 1

4

コードの最後の 4 行を見てください (上記のものは何も使用していません)。

// create a "choc" object using the Chocolate constructor 
// that has a "type" of "milk"

var choc = new Object();
choc.type = "milk";

// print the sweet and type properties of choc
console.log(choc.value);
console.log(choc.type);

Chocolateオブジェクトを作成したり、sweetプロパティを出力したりしませんでした (したがって、 を取得undefinedvalueます)。

代わりに、

var choc = new Chocolate("milk");
console.log(choc.sweet); // true
console.log(choc.type); // "milk"

あなたの更新されたコードは私のために働きます。

于 2012-08-24T16:17:27.297 に答える