gpt4 book ai didi

JavaScript继承: member functions not inheriting?

转载 作者:行者123 更新时间:2023-11-28 19:24:21 26 4
gpt4 key购买 nike

这让我发疯。我快要崩溃并哭泣了。

这是我的代码,不起作用:

// 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()?我真的不想这样做,因为那是糟糕的编程。 >:(

最佳答案

Object.create期望新对象的原型(prototype)作为其参数,而不是构造函数。将您的行更改为此,它将起作用:

ExpensiveShirt.prototype = Object.create(Shirt.prototype);

关于JavaScript继承: member functions not inheriting?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28162099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com