[英]Why isn't this code working when i try to use IFFE
I tried to run this code. 我试着运行这段代码。
var temp = (function () {
var a =10;
return {
function (a) {
console.log('Value of a is ' + a);
}
}
})();
temp();
I expect IIFE to return the function and assign it to the temp variable, but instead, I get the error below. 我希望IIFE返回函数并将其分配给临时变量,但我得到下面的错误。
Uncaught TypeError: temp is not a function
Whats wrong with that? 那有什么不对吗?
You are returning a block inside which a function is defined. 您正在返回一个块,其中定义了一个函数。 Instead return the function directly.
而是直接返回函数。 Please find the below code for reference.
请查看以下代码以供参考。
var temp = (function () {
var a =10;
return function (a) {
console.log('Value of a is ' + a);
}
})();
temp();
And if you want to access the value of 'a' from the outer scope then use a different name for the parameter in the inner function. 如果要从外部作用域访问“a”的值,则在内部函数中为参数使用不同的名称。
var temp = (function () {
var a =10;
return function (b) {
a = b || a;
console.log('Value of a is ' + a);
}
})();
temp();
You need to remove the object literals from the return & return a named function 您需要从返回中删除对象文字并返回一个命名函数
var temp = (function() { var a = 10; return function test(a) { console.log('Value of a is ' + a); } })(); temp();
I guess you got confused with '{}' instead of '()'. 我猜你与'{}'而不是'()'混淆了。
var temp = (function () {
var a =10;
return (
function (a) {
console.log('Value of a is ' + a);
}
)
})();
temp(<pass 'a' here>);
Further you are returning a function definition, which is not bound to 'a'. 此外,您将返回一个函数定义,该定义未绑定到“a”。 Try calling 'temp' with an argument.
尝试用参数调用'temp'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.