这个问题在这里已有答案:
对象文字声明中的自引用 20个答案在Gulp.js文件中(但它可以是任何Javascript文件)我在Javascript对象中设置路径:
var paths = { devDir : 'builds/development/', devDirGlobs : this.devDir+'*.html' }现在,正如您所看到的,我正在尝试将属性“ devDirGlobs ”中的属性“ devDir ”记为“ this.devDir ”。
它不起作用,但它也没有给我任何错误?
任何提示?
在此先感谢您的帮助!
This question already has an answer here:
Self-references in object literals / initializers 23 answersIn a Gulp.js file (but it can be any Javascript file) I set the paths in a Javascript object:
var paths = { devDir : 'builds/development/', devDirGlobs : this.devDir+'*.html' }Now, as you can see, I'm trying to recall the property "devDir" in the value of the property "devDirGlobs", as "this.devDir".
It doesn't work, but also it doesn't give to me any error?
Any hint?
Thanks in advance for your help!
最满意答案
在声明对象之前,无法访问对象的属性。
但是,您可以使用点语法而不是文字来构造对象。
var paths = {} paths.devDir = 'builds/development/'; paths.devDirGlobs = paths.devDir + '*.html';或者将常用值移动到共享配置对象中。
var config = { dir: 'builds/development' }; var paths = { devDir : config.dir, devDirGlobs : config.dir + '*.html' };It's not possible to access the properties of the object before the object has been declared.
However, you could construct the object with dot syntax rather than as a literal.
var paths = {} paths.devDir = 'builds/development/'; paths.devDirGlobs = paths.devDir + '*.html';Or move common values into a shared config object.
var config = { dir: 'builds/development' }; var paths = { devDir : config.dir, devDirGlobs : config.dir + '*.html' };更多推荐
发布评论