gpt4 book ai didi

javascript - 为什么使用自执行函数?

转载 作者:行者123 更新时间:2023-12-03 00:17:46 30 4
gpt4 key购买 nike

在很多地方我都看到这样的脚本:

(function () {
var hello = 'Hello World';
alert(hello);
})();

为什么不直接这样写,不带任何函数:

var hello = 'Hello World';
alert(hello);

最佳答案

我们使用自执行函数来管理变量范围

变量的作用域是定义它的程序区域。全局变量具有全局作用域;它在 JavaScript 代码中随处定义。 (即使在您的职能中)。另一方面,在函数内声明的变量仅在函数体内定义。它们是局部变量并且具有局部作用域。函数参数也算作局部变量,并且仅在函数体内定义。

var scope = "global";
function checkscope() {
alert(scope);
}

checkscope(); // global

如您所见,您可以访问函数内的 scope 变量,但是,在函数体内,局部变量优先于同名的全局变量。如果您声明与全局变量同名的局部变量或函数参数,则实际上隐藏了全局变量。

var scope = "global";
function checkscope() {
var scope = "local";
alert(scope);
}

checkscope(); // local
alert(scope); // global

如您所见,函数内的变量不会覆盖全局变量。由于这个特性,我们将代码放在自执行函数中,以防止当我们的代码变得越来越大时覆盖其他变量。

// thousand line of codes
// written a year ago

// now you want to add some peice of code
// and you don't know what you have done in the past
// just put the new code in the self executing function
// and don't worry about your variable names

(function () {
var i = 'I';
var can = 'CAN';
var define = 'DEFINE';
var variables = 'VARIABLES';
var without = 'WITHOUT';
var worries = 'WORRIES';

var statement = [i, can, define, variables, without, worries];

alert(statement.join(' '));
// I CAN DEFINE VARIABLES WITHOUT WORRIES
}());

关于javascript - 为什么使用自执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17058606/

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