与knockout.js函数覆盖的Javascript

时间:2013-06-26 13:22:27

标签: javascript inheritance knockout.js

我有一个基本的viewmodel如下:

var myApp = myApp || {};

myApp.BaseViewModel = function () {
    self = this;
    self.var1 = ko.observable();
    self.messageToSay = Function() {
        alert("in Base view model");
    };
    self.sayMessage = function() {
        self.messageToSay();
    }
};

我有一个从BaseViewModel继承的viewmodel,如下所示:

var myApp = myApp || {};

myApp.HomeViewModel = function() {

   var self = this;
   ko.utils.extend(self. new myApp.BaseviewModel());

   self.messageToSay = Function() {
        alert("in Home view model");
    };

};

var vm = new myApp.HomeViewModel();
ko.applyBindings(vm, vm);

问题是当我执行vm.sayMessage()时总是返回“在基本视图模型中”而不是“在主视图模型中”。如何在HomeViewModel中获取messageToSay()方法以覆盖BaseViewModel()中的方法?

由于 马丁

1 个答案:

答案 0 :(得分:2)

这是你应该执行继承的方式:

myApp.HomeViewModel = function() {

   var self = this;
   myApp.BaseviewModel.apply(self, [/*BaseViewModel constructor args */]);

   self.messageToSay = function() {
        alert("in Home view model");
    };

};

See fiddle

我希望它有所帮助。