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. >:(

Community
  • 1
  • 1
Dan Mantyla
  • 1,840
  • 1
  • 22
  • 33

2 Answers2

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);
Paul
  • 139,544
  • 27
  • 275
  • 264
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.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299