gpt4 book ai didi

javascript - 下面的 JavaScript 代码片段在做什么

转载 作者:行者123 更新时间:2023-11-28 00:45:31 25 4
gpt4 key购买 nike

我在学习 Javascript 时看到如下一些代码片段,我对此不太确定,您能告诉我这个结构到底是做什么的,以及何时使用吗?

(function abc() 
{
//action code here
})();

示例

(function test() {
alert(1);
})();

非常感谢。

最佳答案

您能做的最好的事情就是阅读这篇文章:

JavaScript Module Pattern: In-Depth

小引用:

Anonymous Closures

This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We’ll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.

(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());

但是,真正阅读这篇文章并观察我们所拥有的内容,感谢其他人为我们描述了 JS 模式......

因为更重要的是 MODULE 模式

Module Export

Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value. Doing so will complete the basic module pattern, so here’s a complete example:

var MODULE = (function () {
var my = {},
privateVariable = 1;

function privateMethod() {
// ...
}

my.moduleProperty = 1;
my.moduleMethod = function () {
// ...
};

return my;
}());

关于javascript - 下面的 JavaScript 代码片段在做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com