gpt4 book ai didi

Javascript 继承 codecademy

转载 作者:行者123 更新时间:2023-11-28 16:13:46 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com