模块化的方式来导入对象实例

我正在寻找一种方法来定义javascript文件中的对象实例,就像这样。

以下内容位于文件serviceKnex.js

 import Knex from 'knex' var knex = Knex({ client: 'mysql', connection: { host : '127.0.0.1', user : 'your_database_user', password : 'your_database_password', database : 'myapp_test' }, migrations: { tableName: 'migrations' } }) export default knex 

然后能够import serviceKnex.js并直接在这样的函数中使用它。

 import serviceKnex from '../serviceKnex' export async function createItem () { return serviceKnex('table') .insert({'hello', 'world'}) } 

不过,我想使上面的代码是一个npm模块,理想情况下可以接受serviceKnex对象作为参数。 我仍然希望这个函数的使用者能够改变他们正在使用的knex对象实例。

有没有办法允许一个简单的模块化,可交换的接口来导入和使用全局对象实例?

我试图阻止自己写这样的函数,通过knex对象。

 export async function createItem (knex) { return knex('table') .insert({'hello', 'world'}) } 

您可以创build一个包装类,它将serviceKnex作为构造函数中的一个参数,另外还提供了一个setKnex()方法。

例:

 export default class DatabaseClass { constructor(serviceKnex) { this.serviceKnex = serviceKnex; } setKnex(knexService) { this.serviceKnex = serviceKnex; } async createItem() { return this.serviceKnex('table') .insert({'hello', 'world'}); } } 

那么你会这样使用它:

 import serviceKnex from '../serviceKnex'; import DatabaseClass from 'database-class'; var dbObject = new DatabaseClass(knexService); dbObject.createItem(); 

如果你不想使用类,你可以在修改全局variables的NPM模块代码中添加一个setter函数,但是我个人更喜欢包装类方法。

你考虑过原型inheritance吗? 类似于jQuery的构build方式,大致如下:

 function serviceKnex (knexInstance) { return new init(knexInstance) } function init (knexInstance) { this.instance = knexInstance return this } init.prototype = { createItem () { return this.instance('table').insert({'hello', 'world'}) } } export default serviceKnex 

那么你的用户将能够使用不同的实例。

 import Knex from 'knex' import serviceKnex from 'serviceKnex' const knexOne = Knex({}) const knexTwo = Knex({}) const serviceKnexOne = serviceKnex(knexOne) const serviceKnexTwo = serviceKnex(knexTwo) serviceKnexOne.createItem() serviceKnexTwo.createItem() 

编辑:或与ES6类,因为这个答案指出。