节点.js模块 - 将所需对象方法附加到主 App 对象

Node.js Module - attach required objects methods to main App object

本文关键字:对象 方法 App 模块 js 节点      更新时间:2023-09-26

对不起,如果标题有点模糊,我真的不知道该怎么称呼这个概念。

基本上我有一个包含以下代码的主.js文件:

var util = require('./folder/util');
var summoner = require('./folder/player');
var App = {
  timeout: 500,
  apiKey: 'asdnanfasofafasqrqrsa',
  region: 'can'
}
App.init = function(apiKey, region) {
  this.apiKey = apiKey;
  this.region = region;
}
App.getPlayerByName = player.getPlayerByName;
module.exports = App;

我还有一个包含这些方法的播放器.js文件(player.getPlayerByName)。我的目标是使用该主入口文件创建一个 NPM 模块.js并像这样访问它:

var main = require('main.js');
main.getPlayerByName('Jake');

现在,我发现将这些方法"附加"到该主 App 对象以便我可以如上所述访问它的唯一方法是将以下代码行添加到 main.js:

App.getPlayerByName = player.getPlayerByName;

它按原样运行良好,但是在我向播放器.js文件添加更多方法后,我将在主文件中出现很多我不介意避免的额外膨胀.js。有没有更好的方法呢?

提前谢谢你!

您可以迭代播放器对象并将所有方法复制到App对象:

var App = {
  timeout: 500,
  apiKey: 'asdnanfasofafasqrqrsa',
  region: 'can'
}
App.init = function(apiKey, region) {
  this.apiKey = apiKey;
  this.region = region;
}
// copy all methods from player to App
for (var method in player) {
    if (player.hasOwnProperty(method) && typeof player[method] === "function") {
        App[method] = player[method];
    }
}

只要player只是一个命名空间对象,其中方法不使用实际的对象实例,这将起作用。


或者,您可以只使用现有的player对象,并将自己的属性分配给该现有对象:

Object.assign(player, {
    timeout: 500,
    apiKey: 'asdnanfasofafasqrqrsa',
    region: 'can',
    init: function(apiKey, region) {
        this.apiKey = apiKey;
        this.region = region;
    }
});
module.exports = player;

在这两种情况下,都必须确保对象的两种用法之间没有方法/属性名称冲突。