簡體   English   中英

ES6計算屬性和嵌套模板文字

[英]ES6 Computed Property & nested template literal

請看下面的代碼:

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 而不是外部定義它。

至於${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}` },
}

而且我不想在process.env.MYAPP_...使用字符串文字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']}`)

謝謝大家,全力以赴!

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

上面的方法不能在聲明config時起作用, this.prefixundefined 如果您登錄config將會得到類似以下的內容。 注意undefined_HOST

{prefix: "MYAPP", MYAPP_HOST: "2", undefined_HOST: "localhost"}

相反,請嘗試跟隨,如果您確實想這樣做,

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

沒有嵌套模板文字之類的東西,因為它不是必需的。 如此答案中所述 ,這是通過模板文字和常規JS中的括號表示的。 它應該是:

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}`
}

通常甚至不需要這樣做,因為此模板文字非常混亂且難以閱讀。 模板文字的目的是提供格式正確的串聯字符串,而這違背了目的。

可以使用樣式正確的第三方代碼中的臨時變量來查看此類表達式-是的,無需括號即可實現:

url: function () {
  const host = process.env[`${this.prefix}_HOST`] || this.db.host;
  ...
  return `driver:/${host}:${port}/${name}`;
}

整潔,干凈,不需要太長的線條,而不會導致棉絨錯誤。

原始代碼段無效,因為您無法在定義對象文字時引用其屬性 (如@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 ,你也可以指config直接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM