简体   繁体   English

Javascript引用它自己的对象内部的值

[英]Javascript referencing values inside the object it self

I have a config file for my Node.js application which looks like this: 我有一个我的Node.js应用程序的配置文件,如下所示:

// Development specific configuration
// ==================================
module.exports = {

....

  ip: "localhost",
  //Rabbit MQ
  rabbitmq: {
    username: 'foo',
    password: 'bar',
    ip: 'amqp://'+this.username+':'+this.password+'@rabbitmq',
    queues: {
      name: 'foo'
    }
  }, 
....

};

Here is what the module looks like where I use this config file: 以下是我使用此配置文件时模块的外观:

var config = require ('../../config/environment');
this.con = amqp.connect (config.rabbitmq.ip);

I am getting undefined for the username and password: 我的用户名和密码未定义:

amqp://undefined:undefined@rabbitmq

I have tried multiple ways such as: 我尝试了多种方法,例如:

  1. Creating getter functions inside the object like this: 在对象内创建getter函数,如下所示:

     rabbitmq: { username: 'foo', password: 'bar', getUsername: function (){ return this.username; }, getpassword: function (){ return this.password; }, ip: 'amqp://'+this.getUsername()+':'+this.getpassword()+'@rabbitmq', 
  2. Created a self value and assign 'this' and reference it: 创建一个自我值并指定'this'并引用它:

     self: this, ... ip: 'amqp://'+self.rabbitmq.username+':'+self.rabbitmq.password+'@rabbitmq', 

    .. ..

I cannot get the scope to properly work. 我无法让范围正常工作。 Am I missing something basic? 我错过了什么基本的东西? How can I make this happen? 我怎样才能做到这一点? Please help. 请帮忙。

This will work: 这将有效:

var username = 'foo';
var password = 'bar';

module.exports = {
  ip: "localhost",
  //Rabbit MQ
  rabbitmq: {
    username: username,
    password: password,
    ip: 'amqp://'+username+':'+password+'@rabbitmq',
    queues: {
      name: 'foo'
    }
  }
};

You can do something like this: 你可以这样做:

var config = {
    ip : "localhost", //Rabbit MQ
    rabbitmq : {
        username : 'foo',
        password : 'bar',
        queues : {
            name : 'foo'
        }
    }
};

config is now declared in module scope so you can reuse its values config现在在模块范围内声明,因此您可以重用其值

config.rabbitmq.ip = 'amqp://' + config.rabbitmq.username + ':' + config.rabbitmq.password + '@rabbitmq';
module.exports = config;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM