【发布时间】:2015-01-27 02:10:30
【问题描述】:
这快把我逼疯了。我快要崩溃和哭泣了。
这是我的代码不起作用:
// 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
现在,如果我添加这些行,那么它可以工作:
ExpensiveShirt.prototype.getPrice = Shirt.prototype.getPrice;
ExpensiveShirt.prototype.display = Shirt.prototype.display;
但据此我不应该这样做:JavaScript inheritance with Object.create()? 我真的不想这样做,因为那是糟糕的编程。 >:(
【问题讨论】:
-
不要混合表示逻辑和数据...
标签: javascript oop inheritance