【问题标题】:JavaScript inheritance: member functions not inheriting?JavaScript继承:成员函数不继承?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • errmerrgerrdddd 非常感谢!我的大脑今天没有完全工作。
【解决方案2】:

正如@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>

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2017-01-05
    • 2013-05-09
    • 2016-06-24
    • 1970-01-01
    • 2012-02-13
    • 2012-04-12
    • 1970-01-01
    相关资源
    最近更新 更多