为什么要在这个 var 声明中将这个变量赋值给它自己?
我正在阅读 Ben Cherry 的“JavaScript 模块模式:深入”,他有一些我不太理解的示例代码。在跨文件私有状态标题下,有一些示例代码,其中包含以下内容:
var _private = my._private = my._private || {}
这似乎与编写这样的内容没有什么不同:
var _private = my._private || {}
这里发生了什么以及这两个声明有何不同?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行表示如果存在
my._private
,则使用它,否则创建一个新对象并将其设置为my._private
。一条语句中可以使用多个赋值表达式。赋值运算符使用(消耗)其右侧的任何内容,并生成该值作为被分配变量左侧的输出。因此,在本例中,为了清楚起见,使用括号,上面的内容相当于
var _private = (my._private = (my._private || {}))
这种情况是 延迟初始化。一个不太简洁的版本是:
在这种情况下,惰性初始化似乎更多地用于任何地方初始化而不是惰性。换句话说,所有函数都可以包含此行来安全地创建或使用
my._private
,而不会破坏现有的 var。This line means use
my._private
if it exists, otherwise create a new object and set it tomy._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:
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.