我无法理解是什么让这个函数自行执行。有人可以解释一下吗?谢谢
var iCallMySelf = function(){
console.log("Hi there :D");
}
(function(){})
最佳答案
这是一个函数
function(){
console.log("Hi there :D");
}
如果您将此函数分配给一个变量,您就可以执行它 - 这是最正常的方式:
foo = function(){
console.log("Hi there :D");
}
foo()
但是,您可以在声明函数时使用末尾的那些括号直接执行该函数。您必须将其括在方括号中以使其成为一条声明才能正常工作:
(function(){
console.log("Hi there :D");
})()
赋值也是一个语句,所以这也适用于执行函数:
var iCallMySelf = function(){
console.log("Hi there :D");
}()
最后,当你执行它时,你可以在末尾的那些括号中传入参数:
var iCallMySelf = function(){
console.log("Hi there :D");
}(1, 2, 3)
或者,在您的示例中,您将另一个函数作为参数传递:
var iCallMySelf = function(){
console.log("Hi there :D");
}
(
// This is a function being passed as an argument to the function above
function(){}
)
你可以像这样用你传入的 arg 做一些事情:
var iCallMySelf = function(foo){
console.log("Hi there :D");
// foo is the function you pass in below
console.log(foo)
}
(
// This is a function being passed as an argument to the function above
function(){}
)
希望对您有所帮助!
关于javascript - 为什么这个javascript函数自己执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26382261/