问题
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