重复的构造函数

时间:2015-02-20 11:40:27

标签: javascript

如何在多个对象中重用相同的构造函数?

此处creditor_group在两个对象中构建。如何复制Delegate函数!?

http://jsfiddle.net/q2nxuhyc/2/

var App = {};
App.module_group = function(main, location, table){
    this.init = function(){
        console.log('init: '+table+' args: '+main+', '+location);
    };

    this.test = function(){
        console.log('test: '+table);
    };
};

function Delegate(main, location){
    this.table;
    this.module_name;

    var module;

    this.init = function(){
        module = new App[this.module_name](main, location, this.table);
        module.init();

        return module;
    };

    this.test = function(){
        module.test();
    };
}

var module_1 = Delegate;
module_1.prototype.table = 'debtor_group';
module_1.prototype.module_name = 'module_group';

var module_2 = Delegate;
module_2.prototype.table = 'creditor_group';
module_2.prototype.module_name = 'module_group';

// This part where the objects are constructed is done in another scope
var m_1 = new module_1('main', 'location');
m_1.init();
m_1.test();
var m_2 = new module_2('main', 'location');
m_2.init();
m_2.test();

控制台

init: creditor_group args: main, location
test: creditor_group
init: creditor_group args: main, location
test: creditor_group

1 个答案:

答案 0 :(得分:2)

听起来你想要继承两个额外的构造函数module_1module_2,它们都调用Delegate

function Delegate(main, location) {
    this.module = null;
    this.init = function() { // you should do initialisation stuff directly in the
                             // constructor, not an `init` method
        this.module = new App[this.module_name](main, location, this.table);
        this.module.init();
    };
}
Delegate.prototype.test = function(){
    this.module.test();
};

function Module_1(main, location) {
    Delegate.call(this, main, location);
}
Module_1.prototype = Object.create(Delegate.prototype);
Module_1.prototype.table = 'debtor_group';
Module_1.prototype.module_name = 'module_group';


function Module_2(main, location) {
    Delegate.call(this, main, location);
}
Module_2.prototype = Object.create(Delegate.prototype);
Module_2.prototype.table = 'creditor_group';
Module_2.prototype.module_name = 'module_group';