简体   繁体   English

当我尝试使用IFFE时,为什么这段代码不起作用?

[英]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.

相关问题 当我使用 fetch my.then 代码不起作用 - When I use fetch my .then code isn't working 试图使用链接延迟,但我尝试的任何代码都无法正常工作 - Trying to use a link delay, but any code I try isn't working 当我尝试通过ID提取标签时,为什么我的jQuery无法正常工作? - why isn't my jQuery working when I try to fetch a tag by Id? 为什么当我尝试在滚动时更改它时我的旋转 css 不起作用? - why my rotate css isn't working when I try to change it while scroll? 为什么我测试时我的Three.js代码无效? - Why my Three.js code isn't working when i test it? 为什么要使用IFFE闭包而不是常规闭包? - Why use an IFFE closure over a regular closure? 帆布屋。 将代码复制到编辑器并在浏览器中运行时,为什么代码不起作用? - Canvas- house. Why isn`t the code working, when I copy it to an editor and run it in my browser? 为什么我的函数在Parse Cloud Code中不起作用? 当我在Angular和Express中测试时它可以工作 - Why isn't my function working in Parse Cloud Code? It works when I test in Angular and Express 当我将其导入Wordpress网站时,为什么我的JQuery / CSS代码不起作用? - Why isn't my JQuery/CSS code working when I import it into my Wordpress website? 当我尝试在我的代码中使用它来检查变量时,if 语句不起作用 - if statement not working when i try to use it in my code to check a variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM