0

使用下面给出的代码,我正在尝试输出 choc 的值和类型,而巧克力的类型和牛奶却未定义。有人可以帮我理解如何输出类型吗?我已经为此工作了一段时间,但它并没有点击我。谢谢!

// 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

查看代码的最后四行(它不使用上面的任何内容):

// 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属性(因此得到undefinedfor value)。

相反,使用

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

您更新的代码对我有用。

于 2012-08-24T16:17:27.297 回答