Javascript继承codecademy

时间:2012-08-24 16:13:55

标签: javascript inheritance

根据下面给出的代码,我试图输出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);

1 个答案:

答案 0 :(得分: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属性(因此undefined获得value)。

相反,请使用

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

您的更新代码适用于我。