When IIFE return a value, where does the value exist?

天涯浪子 提交于 2020-01-24 20:57:35

问题


When I tried the example on babel Symbol in the example there was no return, so I added it cause I thought it should be(I am not sure if I am right).

It logged in my console MyClass is not defined.

If IIFE returns a Class, why it said MyClass is not defined?

(function() {

  var key = Symbol("key");

  function MyClass(privateData) {
    this[key] = privateData;
  }

  MyClass.prototype = {
    doStuff: function() {
    }
  };
  return MyClass //this is no return for the original example
})();

var c = new MyClass("hello")
c["key"] 

回答1:


As with any other function call, the value goes to the left hand side of the function.

var return_value_of_x = x();

or

var return_value_of_iife = (function () { return 1; })();

Since you have nothing on the LHS of your IIFE, the value is discarded.

In your example MyClass is a variable declared within the IIFE. It doesn't exist outside that function. You could create another variable with the same name in the wider scope:

var MyClass = (function () { …



回答2:


You can store the value somewhat like this if your IIFE is returning a value.

let returnedValue = (function(){console.log('return'); return 2;})();


来源:https://stackoverflow.com/questions/45185406/when-iife-return-a-value-where-does-the-value-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!