gpt4 book ai didi

javascript - 复制构造函数

转载 作者:行者123 更新时间:2023-11-30 17:02:16 26 4
gpt4 key购买 nike

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

这里 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

最佳答案

听起来您想对两个调用 Delegate 的额外构造函数 module_1module_2 使用继承:

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';

关于javascript - 复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28628115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com