为什么要在这个 var 声明中将这个变量赋值给它自己?

发布于 2024-12-18 15:32:54 字数 387 浏览 0 评论 0原文

我正在阅读 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不可一世的女人 2024-12-25 15:32:54
var _private = my._private = my._private || {}

此行表示如果存在 my._private,则使用它,否则创建一个新对象并将其设置为 my._private

一条语句中可以使用多个赋值表达式。赋值运算符使用(消耗)其右侧的任何内容,并生成该值作为被分配变量左侧的输出。因此,在本例中,为了清楚起见,使用括号,上面的内容相当于 var _private = (my._private = (my._private || {}))

这种情况是 延迟初始化。一个不太简洁的版本是:

if (!my._private) {
    my._private = {};
}
var _private = my._private;

在这种情况下,惰性初始化似乎更多地用于任何地方初始化而不是惰性。换句话说,所有函数都可以包含此行来安全地创建或使用 my._private ,而不会破坏现有的 var。

var _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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文