[英]When I log typeof an IIFE to the console, it is an object instead of a function, why?
I have an IIFE that returns an object.我有一个返回对象的 IIFE。 In my app.js file, which I add to a script tag in index.html, I log to the console typeof my IIFE and it is an object.
在我添加到 index.html 中的脚本标记的 app.js 文件中,我登录到我的 IIFE 的控制台类型,它是一个对象。 Shouldn't it be a function?
不应该是函数吗? Why is typeof returning an object?
为什么 typeof 返回一个对象?
Here is my IIFE in app.js:这是我在 app.js 中的 IIFE:
var UIController = (function() {
var DOMstrings = {
inputType: '.add__type',
description: '.add__description',
value: '.add__value',
addBtn: '.add__btn'
};
return {
getInput: function() {
// return an object containing all values from UI elements
return {
type: document.querySelector(DOMstrings.inputType).value, // will be either income or expense
description: document.querySelector(DOMstrings.description).value, // description of transaction
value: document.querySelector(DOMstrings.value).value // value of transaction
};
},
getDOMStrings: function() {
return DOMstrings;
}
};
})();
console.log(typeof UIController);
IIFE stands for “immediately invoked function expression.” IIFE 代表“立即调用的函数表达式”。 In other words, an expression created by invoking a function .
换句话说,通过调用函数创建的表达式。 Invoking a function means to call the function and produce a result.
调用函数意味着调用函数并产生结果。 The value of an IIFE is the result of calling (invoking) the function, not the function itself.
IIFE 的值是调用(调用)函数的结果,而不是函数本身。
In your example, the variable UIController
is assigned the result of calling a function.在您的示例中,变量
UIController
被分配了调用函数的结果。 Your function returned an object with two properties.您的函数返回了一个具有两个属性的对象。 The object is assigned to
UIController
.该对象被分配给
UIController
。 So typeof UIController
produces object
as expected.所以
typeof UIController
按预期生成object
。
**REMEMBER Immediately Invoked FUNCTION EXPRESSION FUNCTION (IIFE) are functions whose variables cannot be accessed outside the function & you cannot call that function explicitly(this will give error) ** **记住立即调用的函数表达式函数 (IIFE) 是不能在函数外部访问其变量的函数,并且您不能显式调用该函数(这会出错)**
*here is a simple code to clear concept of IIFE. *这是一个简单的代码来清除IIFE的概念。 this function just prints hey & do not have any return value *
这个函数只是打印嘿&没有任何返回值*
var run=(function(){
console.log("HEY");
})();
run(); //error
console.log(run); HEY
console.log(typeof(run)); undefined
*Below IIFE functions returns the value * *下面的IIFE函数返回值*
var run=(function(){
return 1;
})();
run(); //error
console.log(run); 5
console.log(typeof(run)); number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.