node.js - 一段js代码的简写问题
PHP中文网
PHP中文网 2017-04-17 14:57:06
[Node.js讨论组]

    options.filename = dbPath+'picker';
    pickerDB = new Datastore(options);
    options.filename = dbPath+'data';
    dataDB = new Datastore(options);
    options.filename = dbPath+'web';
    webDB = new Datastore(options);
    options.filename = dbPath+'url';
    urlDB = new Datastore(options);
    options.filename = dbPath+'attach';
    attachDB = new Datastore(options);
    options.filename = dbPath+'cacheUrl';
    cacheUrlDB = new Datastore(options);
    options.filename = dbPath+'cache';
    cacheDB = new Datastore(options);
    options.filename = dbPath+'cron';
    cronDB = new Datastore(options);
    options.filename = dbPath+'log';
    logDB = new Datastore(options);
    options.filename = dbPath+'cronLog';
    cronLogDB = new Datastore(options);

请教一下,这一大段,都是复制粘贴。能用更简洁的代码一次搞定吗?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
伊谢尔伦

不知道算不算你心中的简写,我觉得从重复的角度看,把不同的部分提取出来做个数组,把相同的部分抽象,如下:

let options = {},
    dbPath = ''; //TBD by yourself

let stores = [
    'picker',
    'data',
    'web',
    'url',
    'attach',
    'cacheUrl',
    'cache',
    'cron',
    'log',
    'cronLog']
    .map(key => (options.filename = dbPath + key, new Datastore(options)));


console.log(stores); //stores you want
PHP中文网
    /*
        options == ?
        dbPath == ?
    */
    var _Datastore = {};
    _Datastore._opts = options;
    _Datastore._path = dbPath;
    _Datastore.Create = function(pathAddon){
        this._opts.filename = this._path + pathAddon;
        return new Datastore(this.options);
    };
    
    pickerDB = _Datastore.Create('picker');
    dataDB = _Datastore.Create('data');
    webDB = _Datastore.Create('web');
    urlDB = _Datastore.Create('url');
    attachDB = _Datastore.Create('attach');
    cacheUrlDB = _Datastore.Create('cacheUrl');
    cacheDB = _Datastore.Create('cache');
    cronDB = _Datastore.Create('cron');
    logDB = _Datastore.Create('log');
    cronLogDB = _Datastore.Create('cronLog');

不知道你接下来的代码怎么用?如果后边的逻辑代码好改,可以改成:

    var _Datastore = {};
    _Datastore._opts = options;
    _Datastore._path = dbPath;
    _Datastore._cache = {};
    _Datastore.Create = function(pathAddon){
        this._opts.filename = this._path + pathAddon;
        return new Datastore(this.options);
    };
    _Datastore.DB = function(pathAddon){
        this._cache[pathAddon] = this._cache[pathAddon] || this.Create(pathAddon);
        return this._cache[pathAddon];
    };

    
    //调用 cronLogDB 时 改成 
    _Datastore.DB('cronLog');
    
    //第一次 会创建,第二次直接用之前创建的实例
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号