Javascript Knockout.js ViewModels中的继承

Javascript Knockout.js ViewModels中的继承,javascript,knockout.js,prototypal-inheritance,Javascript,Knockout.js,Prototypal Inheritance,我的5个视图模型中的每一个都有一个rowNumber属性。此外,还有一个基于rowNumber属性的计算可观测值。代码如下: function EntityViewModel() { this.rowNumber = ko.observable(); this.isOdd = ko.computed(function () { return this.rowNumber() % 2 != 0; }, this); this.isEven = k

我的5个视图模型中的每一个都有一个rowNumber属性。此外,还有一个基于rowNumber属性的计算可观测值。代码如下:

function EntityViewModel() {
    this.rowNumber = ko.observable();

    this.isOdd = ko.computed(function () {
        return this.rowNumber() % 2 != 0;
    }, this);

    this.isEven = ko.computed(function () {
        return this.rowNumber() % 2 == 0;
    }, this);
}
我有一个从EntityViewModel继承的CountryViewModel,如下所示:

CountryViewModel.prototype = new EntityViewModel();

function CountryViewModel() {
    this.id = ko.observable();
    this.name = ko.observable();
    this.abbrev = ko.observable();
}
var cvm = new CountryViewModel();
cvm.rowNumber(index);
问题: 我现在可以按如下方式设置CountryViewModel对象的行数:

CountryViewModel.prototype = new EntityViewModel();

function CountryViewModel() {
    this.id = ko.observable();
    this.name = ko.observable();
    this.abbrev = ko.observable();
}
var cvm = new CountryViewModel();
cvm.rowNumber(index);

在我的例子中,计算的可观测isOdd/isEven没有得到正确的计算。虽然我通过CountryViewModel设置了行数,但行数似乎为0。计算出的可观测函数是否有任何问题?尤其是设置为该函数的上下文?

您可以执行以下操作,而不是使用原型:

function EntityViewModel() {
    // ...
}
function CountryViewModel() {
    EntityViewModel.apply(this);
}
我更新了您的JSFIDLE作为示例:

似乎在起作用。您能为我们提供一个关于这个问题的更多细节的JSFIDLE吗?嗯,需要knockout.js,所以JSFIDLE可能无法工作。我发现所有国家/地区视图模型的值都是20(最后一行数),但不确定如何修复它?我的JSFIDLE还包括Knockout.js-您可以在左侧的“管理资源”选项卡中添加资源(js和CSS)。请用你的问题做一个工作示例。谢谢马可,我已经附上了jFiddle-