[removed] Mixing constructor pattern and Revealing

2019-07-19 01:26发布

问题:

Is there any way I can do have a Javascript class that extends an object that was created through the revealing module pattern? I tried the following code, but is there away to achieve the same thing?

sv.MergeQuestionViewModel = function () {
    this = sv.QuestionDetailViewModal();
    this.init($("#mergeQuestionModel"));
};  

sv.QuestionDetailViewModal = function () {
    var $el,
        self = this,
        _question = ko.observable(),
        _status = new sv.Status();

    var _init = function (el) {
        $el = el;
        $el.modal({
            show: false,
            backdrop: "static"
        });
    };

    var _show = function () {
        $el.modal('show');
    };

    var _render = function (item) {
        _question(new sv.QuestionViewModel(item));
        _show();
    };

    var _reset = function () {
        _question(null);
        _status.clear();
    };

    var _close = function () {
        $el.modal('hide');
        _reset();
    };

    return {
        init: _init,
        show: _show,
        render: _render,
        reset: _reset,
        close: _close
    };
};

回答1:

You could use jQuery.extend to achive this behaviour.

sv.MergeQuestionViewModel = function () {
    $.extend(this, sv.QuestionDetailViewModal);

    this.init($("#mergeQuestionModel"));
};

sv.QuestionDetailViewModal = (function () {
 var el,

 _init = function($el) {
    el = $el;
    console.log('init', el);
 },

 _render = function() {
    console.log('render', el);
 };

 return {
   init : _init,
   render : _render
 };
}());

var view = new sv.MergeQuestionViewModel();
view.render();

Test it on http://jsfiddle.net/GEGNM/