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

In node.js ES6, is it possible to pass in a type and then instantiate it?

本文关键字:一个 类型 然后 实例化 ES6 js node 是否      更新时间:2023-09-26

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

"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工作这通过传递文件名,但对于该类的实例化,我不能真正看到它是如何可能做到的。

当然-你可以像在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);
};

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

相关文章: