如何在JavaScript对象内引用对象键?

4

如何在JavaScript对象内部引用哈希键?例如,我想实际使用“theme”键,我应该使用“this”来引用“theme”吗?

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

你的意思是在对象实例化期间,对吧? - the system
4个回答

7
您可以使用一个方法:
window.EXAMPLE = {
    config : {
        theme: 'example',
        image_path: function () {
            return '/wp-content/themes/' + this.theme + '/img/';
        },
    }
}

当然,这之后你必须通过 EXAMPLE.config.image_path() 访问它。

你可能不应该在 window 上定义任何东西,而是使用当前作用域。


3
唯一的方法是使用函数:
例如:
windows.EXAMPLE {
  config : {
    theme: 'blah', 
    image_path: function () { return '/path/to' + this.theme } 
  } 
} 

2

不使用函数,您需要将其拆分为两个单独的赋值:

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

1
构建对象时(不是已创建的对象,如Kyle的示例所示),我认为无法访问对象的属性,因为它尚未“存在”,除非您使用函数或某些花哨的东西。
我也看不到这样做的理由,因为您可以在image_path值中直接键入"example",或者您可以在定义之前创建一个变量作为“配置”常量。
var CONF_THEME = 'example';
window.EXAMPLE = {
    config : {
        theme: CONF_THEME,
        image_path: '/wp-content/themes/' + CONF_THEME + '/img/'
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接