gpt4 book ai didi

Javascript 函数定义说明

转载 作者:行者123 更新时间:2023-11-29 15:23:10 25 4
gpt4 key购买 nike

谁能给我解释一下 JS 文件中的以下函数

function Init()
{
(function set()
{
-----code---
print "hello";
}
)();
}

如果我调用函数 Init ,它会自动运行函数集还是我需要调用 set() 来运行它?

最佳答案

您需要调用Init 来运行其中的任何代码。现在,里面的代码只是普通的 JavaScript 代码,但是很有趣。让我们看看为什么。


如何

你的内部函数是所谓的IIFE .为了更容易阅读外部函数 (Init),您可以做的是用 IIFE 调用的结果替换内部函数。

这里有几个例子:

var x = undefined; // x === undefined
x = (undefined); // again
x = 3; // x === 3
x = (3); // again the same
x = 'some string'; // some string
x = ('some string'); // the same

所以可以将 () 放在一个对象周围,你会得到相同的对象。一个函数也一样

x = function() {};   // x is that function now.
x = (function() {}); // the same.

但是如果你说x = 3;,你能调用x吗?

x = 3;
x(); // syntax error
x = (3);
x(); // again error. can't call a number.

但是,如果你的 x 是一个函数,你可以调用它:

x = function() { console.log('Hi'); }; // you can call x now.
x(); // logs 'Hi'!

所以如果你对括号做同样的事情,结果是一样的:

x = (function() { console.log('Hi'); }); // again, the same.
x(); // no error, function called again!

所以你可以跳过作业部分:

// instead of x = (...); and the x(), you replace the x part right away.

(function() { console.log('Hi'); })()
// function body up to here ^^ now the call part.

请注意,如果没有第一对括号,它将无法工作:

function() { console.log('Hi'); }(); // syntax error.

因此,您放置外括号 () 只是为了将该函数表达式就地转换为对象。


为什么

这就是它的工作原理。 但为什么呢? 因为您想确保没有其他人调用您的函数!如果你这样做:

var x = function() {};
x();

现在至少有两件您可能不希望发生的事情:

  1. 可能存在名称冲突。您可能不知道在调用外部函数的任何地方是否已经定义了“x”,例如你 bind Init 到某个范围内有 x 的对象。

  2. 有人可以“窃取”您的 x 并再次调用它。不一定偷,你只是泄露了它(一个微妙的错误)和一些其他代码调用 x,期望找到它自己的 x,但实际上,它现在是你的 x,因为它是可达的。而你希望它不是。

因此您可以轻松地将其锁定在立即执行的匿名函数中。

希望这能让事情更清楚一些。

关于Javascript 函数定义说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41814637/

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