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

JavaScript inheritance: member functions not inheriting?

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

我的代码不起作用:

// 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 期望新对象的原型作为其参数,而不是构造函数。将您的行更改为此,它将起作用:

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

正如@Paulpro 提到的,您需要在 Shirt.prototype 上使用 Object.create 而不是 Shirt 才能使继承工作。

在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>

希望对您有所帮助。