根据下面给出的代码,我试图输出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);
答案 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"
您的更新代码适用于我。