如何在JavaScript对象内部引用哈希键?例如,我想实际使用“theme”键,我应该使用“this”来引用“theme”吗?
window.EXAMPLE = {
config : {
theme: 'example',
image_path: '/wp-content/themes/' + this.theme + '/img/',
}
}
如何在JavaScript对象内部引用哈希键?例如,我想实际使用“theme”键,我应该使用“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/';
image_path
值中直接键入"example"
,或者您可以在定义之前创建一个变量作为“配置”常量。var CONF_THEME = 'example';
window.EXAMPLE = {
config : {
theme: CONF_THEME,
image_path: '/wp-content/themes/' + CONF_THEME + '/img/'
}
}