简体   繁体   中英

Javascript Inheritance codecademy

With the code given below, I'm trying to output the value and type of choc and I'm getting undefined for type and milk for chocolate. Can someone please help me understand how to output the type? I've been working on this for awhile and it's not clicking to me. Thanks!

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

//////this is what I changed it to and still doesnt work//////////

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

Look at the last four lines of your code (it does not use anything from above):

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

Neither did you create a Chocolate object, nor did you print the sweet property (therefore getting undefined for value ).

Instead, use

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

Your updated code works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM