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

时间:2015-01-27 02:10:30

标签: javascript oop inheritance

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

这是我的代码无效:

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

在JavaScript中处理继承时,我通常使用以下两个函数来简化生活:

&#13;
&#13;
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());
&#13;
<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>
&#13;
&#13;
&#13;

希望有所帮助。