如何在对象中引用JavaScript对象键

How to reference a JavaScript object key within the object?

本文关键字:对象 JavaScript 引用      更新时间:2023-09-26

如何在对象本身中引用JavaScript散列键?例如,我希望能够实际使用"主题"键。我会用"this"指代"theme"吗?

window.EXAMPLE = {
config : {
    theme: 'example',
    image_path: '/wp-content/themes/' + this.theme + '/img/',
}
}

你可以使用一个方法:

window.EXAMPLE = {
    config : {
        theme: 'example',
        image_path: function () {
            return '/wp-content/themes/' + this.theme + '/img/';
        },
    }
}

当然,你必须通过EXAMPLE.config.image_path()

访问它

您可能也不应该在window上定义东西,而只是使用当前作用域。

唯一的方法是使用函数:

windows.EXAMPLE {
  config : {
    theme: 'blah', 
    image_path: function () { return '/path/to' + this.theme } 
  } 
} 

如果不使用函数,则必须将其拆分为两个单独的赋值:

window.EXAMPLE = {
    config : {
        theme: 'example'
    }
};
window.EXAMPLE.config.image_path = '/wp-content/themes/' + window.EXAMPLE.config.theme + '/img/';

当构造一个对象时(不是一旦它被创建,如Kyle的例子所示),我认为不可能访问对象的属性,因为它还不"存在",除非您使用函数或一些奇特的东西。

我也认为没有理由这样做,因为您可以在image_path值中键入"example",或者您可以在定义之前创建一个变量作为"配置"常数:

var CONF_THEME = 'example';
window.EXAMPLE = {
    config : {
        theme: CONF_THEME,
        image_path: '/wp-content/themes/' + CONF_THEME + '/img/'
    }
}