在另一个值中使用一个值的值



如果我的问题不是100%清楚,请原谅我,希望你能理解我的意思。

我希望能够在 JS 中做这样的事情,我想知道是否有可能:

export const type = {
    link: 'dark-blue',
    text: `${link} f2` // using the value of the first in the second
}

这有效:

const link = 'dark-blue'
export const type = {
    text: link + ' f2'
}

但这样做的问题是,我必须在对象之外分离我的链接变量。

有什么想法吗?

导出对象后,您可以对其进行更改:

export const type = {
  link: 'dark-blue'
}
type.text = `${type.link} f2`;

单例模型可能有效,但您必须执行type.text()

    const type = {
      link: 'red',
      text: function() {
        return `${this.link} f2`
      }
    }
我想

你想做的是引用类型对象中的link变量,但你不能这样做,因为对象还没有创建。

export const type = {
    link: 'dark-blue',
    text: `${link} f2` // using the value of the first in the second
}

所以更好的方法是:

const type = {
    link: 'dark-blue'
};
type.text = `${type.link} f2`;
export type;

可以使用块范围来定义link,然后text将属性设置为type

let type;
{
  const link = "dark-blue", text = `${link} f2`;
  type = {link, text};
}
console.log(type)

最新更新