ES6计算属性&嵌套模板文字

时间:2018-02-18 02:33:04

标签: javascript ecmascript-6 literals

请查看以下代码:

const config = {
  prefix: 'MYAPP',
  MYAPP_HOST: '1',
  MYAPP_HOST: '2',
  [ this.prefix + '_HOST' ]: 'localhost',
}

console.log(`${config.MYAPP_HOST}`)
console.log(`${config.${config.prefix}_HOST}`)

使两个输出都打印localhost的正确方法是什么?

我知道一种制作方法

  [ this.prefix + '_HOST' ]: 'localhost',

工作是将this.prefix定义为一个函数,因此它变为:

  [ this_prefix() + '_HOST' ]: 'localhost',

但是,我希望如此,因为prefix属于const config,因此可以在 const config中定义,而不是< em>外面

至于${config.prefix}_HOST,我只想构建字符串MYAPP_HOST,但是嵌套了模板文字。有没有办法让它成为可能?

修改

  

嵌套模板毫无意义

虽然为什么我需要这样做可能并不明显,因为问题已经简化为专注于技术,这里是一个简化版本我想要的是。看看下面的代码:

const config = {
  prefix: 'MYAPP',
  app: { port: 3000 },
  db: { host: 'localhost', port: 27017, name: 'db' },

  url: function () { return `driver:/${process.env.MYAPP_HOST || this.db.host}:${process.env.MYAPP_PORT || this.db.port}/${process.env.MYAPP_NAME || this.db.name}` },
}

并且我不想在MYAPP中使用字符串文字process.env.MYAPP_...,而是想要使用prefix变量。是否有意义,这是我需要做的。现在怎么做?

更新

上述问题的答案已经在很多地方传播,所以这里是解决方案的简明摘要(对OP):

const prefix = 'MYAPP'
const config = {
  prefix,
  MYAPP_HOST: '1',
  MYAPP_HOST: '2',
  [ prefix + '_HOST' ]: 'localhost',
}
console.log(`${config.MYAPP_HOST}`)
console.log(`${config[config.prefix+'_HOST']}`)

谢谢大家,向大家致敬!

3 个答案:

答案 0 :(得分:2)

config

上述内容无效,因为this.prefix声明时,undefinedconfig。如果您记录undefined_HOST,您会得到类似的内容。注意{prefix: "MYAPP", MYAPP_HOST: "2", undefined_HOST: "localhost"}

const config = {
  prefix: 'MYAPP'
}
config[config.prefix+'_HOST']='localhost'

如果您真的想这样做,请尝试关注,

data = {"state":1,"endTime":1518852709307,"fileSize":000000}
for x in data:
   print(data[x])

答案 1 :(得分:1)

没有嵌套模板文字这样的东西,因为它不是必需的。正如this answer中所解释的,这是通过括号表示法实现的,包括模板文字和常规JS。它应该是:

this.fbLoginManager.registerCallback(this.callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.v("Main", response.toString());
                    setProfileToView(object);
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString(GraphRequest.FIELDS_PARAM, "id, name, email, gender, birthday, picture.type(large)");
            request.setParameters(parameters);
            request.executeAsync();
        }



        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            Toast.makeText(LoginActivity.this.getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
        }

    });

通常甚至没有必要,因为这个模板文字非常混乱,难以阅读。模板文字的目的是提供格式良好的连接字符串,这个字符串无法实现。

这些表达式可以在正确设计的第三方代码中看到临时变量 - 是的,它可以在没有括号表示法的情况下实现:

url: function () {
  return `driver:/${process.env[this.prefix + '_HOST'] || this.db.host}:${process.env[this.prefix + '_PORT'] || this.db.port}/${process.env[this.prefix + '_NAME'] || this.db.name}`
}

很好,干净,不需要很长的线条,可能导致短信错误。

答案 2 :(得分:1)

您的原始代码段不起作用,因为您无法reference properties of the object literal during its definition(正如@Skyler所解释的那样)。

但是,它应该在url 方法中完美地运行。我会写

const config = {
  prefix: 'MYAPP',
  app: { port: 3000 },
  db: { host: 'localhost', port: 27017, name: 'db' },
  prefixed_env(name) {
    return process.env[this.prefix+"_"+name];
    // or, with template literals:
    return process.env[`${this.prefix}_${name}`];
  },
  url() {
    const host = this.prefixed_env("HOST") || this.db.host,
          port = this.prefixed_env("PORT") || this.app.port,
          name = this.prefixed_env("NAME") || this.db.name;
    return `driver:/${host}:${port}/${name}`;
  },
};

而不是this,而是直接can also referconfig

相关问题