0

This is driving me crazy. I'm about to break down and cry.

Here's my code that is NOT working:

// parent class: Shirt
var Shirt = function() {
    this.basePrice = 1;
}
Shirt.prototype.getPrice = function(){return this.basePrice};
Shirt.prototype.display = function(){
    $('ul#products').append('<li>Product: $' + this.getPrice() + '.00</li>');
};

// subclass: ExpensiveShirt inherits from Shirt
var ExpensiveShirt = function() {
    this.basePrice = 5;
};
ExpensiveShirt.prototype = Object.create(Shirt);


// make some objects and test them
var s = new Shirt();
s.display();               // this works
console.log(s.getPrice()); // this works

var e = new ExpensiveShirt();
e.display();               // this does not work!
console.log(e.getPrice()); // does not work

HERE IS THE JSFIDDLE

Now, if I add these lines, then it works:

ExpensiveShirt.prototype.getPrice = Shirt.prototype.getPrice;
ExpensiveShirt.prototype.display = Shirt.prototype.display;

But according to this I shouldn't have to: JavaScript inheritance with Object.create()? And I really don't want to because that is bad programming. >:(

1
  • Do not mix presentation logic and data... Commented Jan 27, 2015 at 2:50

2 Answers 2

2

Object.create expects the prototype for the new object as its argument, not the constructor. Change your line to this, and it will work:

ExpensiveShirt.prototype = Object.create(Shirt.prototype);
Sign up to request clarification or add additional context in comments.

1 Comment

errmerrgerrdddd thank you so much! my brain is not fully working today.
1

As @Paulpro mentions, you need to use Object.create on Shirt.prototype and not Shirt for inheritance to work.

I usually use the following two functions to make my life easier when dealing with inheritance in JavaScript:

var Shirt = defclass({
    constructor: function () {
        this.basePrice = 1;
    },
    getPrice: function () {
        return this.basePrice;
    },
    display: function () {
        alert("Product: $" + this.getPrice() + ".00");
    }
});

var ExpensiveShirt = extend(Shirt, {
    constructor: function () {
        this.basePrice = 5;
    }
});

var s = new Shirt;
var e = new ExpensiveShirt;

s.display();
e.display();

console.log(s.getPrice());
console.log(e.getPrice());
<script>
function defclass(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

function extend(constructor, properties) {
    var prototype = Object.create(constructor.prototype);
    for (var key in properties) prototype[key] = properties[key];
    return defclass(prototype);
}
</script>

Hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.