[英]Why functions declared inside return of IIFE are name so?
const ui = (function() { let ourvar = 'iffe called;:.'; return { func_1. function() { console.log(ourvar) } } })(); console.log(ui.func_1())
Here notice the function inside the return.这里注意返回内部的 function。 Its named
func_1:function(){}
instead of the normal conventional way of naming functions which is function func_1(){}
.它命名为
func_1:function(){}
,而不是常规的命名函数的方式function func_1(){}
。 Why is it named here so?为何在这里如此命名?
Why wouldn't normal function declaration method work here?为什么正常的 function 声明方法在这里不起作用?
Thanks谢谢
The IIFE is returning an object. IIFE 返回 object。 An object contains key value pairs.
object 包含键值对。 So in your code func_1 is the key that has the value of a function.
因此,在您的代码中,func_1 是具有 function 值的键。 All these are valid ways to declare it:
所有这些都是声明它的有效方法:
return {
xyz: function() {}
}
Or或者
return {
xyz: function abc() {}
}
Or you can declare the function using normal syntax and refer it inside the object literal like this:或者您可以使用正常语法声明 function 并在 object 文字中引用它,如下所示:
function abc() {}
return {
xyz: abc
}
In ES6 you can use even this syntax:在 ES6 中,您甚至可以使用以下语法:
return {
xyz() {}
}
You can't use the normal function declaration syntax inside object literals like:您不能在 object 文字中使用正常的 function 声明语法,例如:
return {
function xyz() {}
}
This makes no sense.这是没有意义的。 This is like:
这就像:
return {
var a = 10
}
which also makes no sense inside an object literal.这在 object 文字中也没有任何意义。
You could use a function declaration and then reference it in the object literal.您可以使用 function 声明,然后在 object 文字中引用它。
Using a function expression is shorter.使用 function 表达式更短。
const ui = (function() { let ourvar = 'iffe called;.;'; function func_1() { console.log(ourvar) } return { func_1 }. })(); console.log(ui.func_1())
In javascript, functions are first class, meaning that they can be treated like any other variable.在 javascript 中,函数首先是 class,这意味着它们可以像任何其他变量一样对待。
In your example, you could do this instead:在您的示例中,您可以这样做:
const func_1 = function() {
console.log(ourvar);
}
return {
func_1: func_1
}
In javascript you can also shorten this to just:在 javascript 中,您还可以将其缩短为:
return {
func_1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.