在node.js ES6中,是否可以传入一个类型然后实例化它?

时间:2016-08-23 18:50:18

标签: javascript node.js ecmascript-6 es6-proxy

在我的项目中,我有几个类看起来像这样:

"use strict";
var exports = module.exports = {};
var SystemsDAO = require('./dao/systems/SystemsDAO.js');
var aop = require('./dbAOPUtils.js');
var Proxy = require('harmony-proxy');
var sqlite3 = require('sqlite3').verbose();

/* Wraps a SystemServiceObject and passes in a constructed
 * DAO object as an argument to specified functions. */
exports.SystemsDAOIntercepter = function(obj) {

    let handler = {
        get(target, propKey, receiver) {
           const origMethod = target[propKey];
           return function(...args) {
            console.log('systemDAOIntercepter: BEGIN');

            // Create a reportsdao object and proxy it through an dbSQLiteConnectionIntercepter
            // (So we don't have to create it for every single method) 
            var systemdao = new SystemsDAO('blah');
            var proxSystemDAO = aop.dbSQLiteConnectionIntercepter(systemdao, sqlite3.OPEN_READONLY);

            args.push(proxSystemDAO);

            console.log('propKey: ' + target[propKey]);

            let result = null;

            result = origMethod.apply(this, args);

            console.log('systemsDAOIntercepter: END');
            return result;
           };
        }
    };

    return new Proxy(obj, handler);
};

是否可以为参数传递一个类型,这样我只需要一个DAOIntercepter类,而不是每个数据访问对象一个类?

我可以通过传递文件名来查看require() SystemsDAO为此工作的部分,但至于该类的实例化,我无法真正看到它是如何可能的那样做。

1 个答案:

答案 0 :(得分:2)

当然 - 您可以像在javascript中的任何其他变量一样传递类。

请注意,现在提供DAOType并在方法内实例化。

"use strict";
var exports = module.exports = {};
var aop = require('./dbAOPUtils.js');
var Proxy = require('harmony-proxy');
var sqlite3 = require('sqlite3').verbose();

/* Wraps a SystemServiceObject and passes in a constructed
 * DAO object as an argument to specified functions. */
exports.makeInterceptor = function(DAOType, obj) {

    let handler = {
        get(target, propKey, receiver) {
           const origMethod = target[propKey];
           return function(...args) {
            console.log('systemDAOIntercepter: BEGIN');

            // Create a reportsdao object and proxy it through an dbSQLiteConnectionIntercepter
            // (So we don't have to create it for every single method) 
            var dao = new DAOType('blah');
            var proxSystemDAO = aop.dbSQLiteConnectionIntercepter(dao, sqlite3.OPEN_READONLY);

            args.push(proxSystemDAO);

            console.log('propKey: ' + target[propKey]);

            let result = null;

            result = origMethod.apply(this, args);

            console.log('makeInterceptor: END');
            return result;
           };
        }
    };

    return new Proxy(obj, handler);
};

我必须承认,我(个人)更愿意看到类在外部实例化并通过参数注入,但是,而不是内联创建它。