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