admin管理员组文章数量:1432573
I was reading Ben Cherry's "JavaScript Module Pattern: In-Depth", and he had some example code that I didn't quite understand. Under the Cross-File Private State heading, there is some example code that has the following:
var _private = my._private = my._private || {}
This doesn't seem to be different from writing something like this:
var _private = my._private || {}
What's happening here and how are these two declarations different?
I was reading Ben Cherry's "JavaScript Module Pattern: In-Depth", and he had some example code that I didn't quite understand. Under the Cross-File Private State heading, there is some example code that has the following:
var _private = my._private = my._private || {}
This doesn't seem to be different from writing something like this:
var _private = my._private || {}
What's happening here and how are these two declarations different?
Share Improve this question edited Nov 29, 2011 at 19:27 jcolebrand 16k12 gold badges77 silver badges122 bronze badges asked Nov 29, 2011 at 19:11 JoeM05JoeM05 9222 gold badges10 silver badges27 bronze badges 2-
1
We are obviously missing context but the second example does not set
my._private
... :-? – Álvaro González Commented Nov 29, 2011 at 19:27 - @ÁlvaroG.Vicario you're correct in that the second example is not the same as the first. – jcolebrand Commented Nov 29, 2011 at 19:30
1 Answer
Reset to default 7var _private = my._private = my._private || {}
This line means use my._private
if it exists, otherwise create a new object and set it to my._private
.
More than one assignment expression can be used in a statement. The assignment operator uses (consumes) whatever is to the right of it and produces that value as its output to the left of the variable being assigned. So, in this case, with parentheses for clarity, the above is equivalent to var _private = (my._private = (my._private || {}))
This case is a type of lazy initialization. A less terse version would be:
if (!my._private) {
my._private = {};
}
var _private = my._private;
In this case, it seems that the lazy initialization is more used for anywhere initialization than laziness. In other words, all functions can include this line to safely create or use my._private
without blowing away the existing var.
本文标签: javascriptWhy assign this variable to itself in this var declarationStack Overflow
版权声明:本文标题:javascript - Why assign this variable to itself in this var declaration? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745607282a2665907.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论