简体   繁体   English

JavaScript继承:成员函数不继承吗?

[英]JavaScript inheritance: member functions not inheriting?

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 这是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()? 但是据此我不必: 继承Object.create()的JavaScript? 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. Object.create期望新对象的原型作为其参数,而不是构造函数。 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. 正如@Paulpro提到的那样,您需要在Shirt.prototype上使用Object.create ,而不是Shirt才能使继承起作用。

I usually use the following two functions to make my life easier when dealing with inheritance in JavaScript: 我通常使用以下两个函数来简化使用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. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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