Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

javascript - 对象常量/初始化程序中的自引用(Self-references in object literals / initializers)

Is there any way to get something like the following to work in JavaScript?(有什么办法可以使以下内容在JavaScript中起作用?)

var foo = { a: 5, b: 6, c: this.a + this.b // Doesn't work }; In the current form, this code obviously throws a reference error since this doesn't refer to foo .(在当前形式中,该代码明显抛出一个参考错误,因为this不是指foo 。) But is there any way to have values in an object literal's properties depend on other properties declared earlier?(但是, 是否有任何方法可以使对象文字的属性值取决于先前声明的其他属性?)   ask by kpozin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the only thing that I can tell you about are getters:(好吧,我唯一能告诉您的就是吸气剂:)

var foo = { a: 5, b: 6, get c() { return this.a + this.b; } } console.log(foo.c) // 11 This is a syntactic extension introduced by the ECMAScript 5th Edition Specification, the syntax is supported by most modern browsers (including IE9).(这是ECMAScript 5th Edition规范引入的语法扩展,大多数现代浏览器(包括IE9)都支持该语法。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...