Javascript 继承 codecademy

标签 javascript inheritance

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

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

最佳答案

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

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

您更新的代码对我有用。

关于Javascript 继承 codecademy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113034/

相关文章:

C++ 声明对象时可以实现虚方法吗?

java - 向不可扩展类 java 添加新功能

c++ - 基类中使用 this 指针的模板函数

java - 为什么我会收到以下错误以及空构造函数中应该有什么?

javascript - Angular 组件路由器从 URL 中删除 #

javascript - 如何管理状态?

javascript - 事件处理程序会发生什么?

javascript - 这个箭头怎么画?

java - 通过 OBJECTS 与 INHERITANCE 访问方法

javascript - vue a-href下载不下载