I am currently doing some experiment about scoping and hoisting in JS.Here i have two example which confusing me in a different way.First i have assigned a anonymous function to a variable named parent.Obviously returned child function has access to its outer function scope so it can access text variable.It is clear and easy.Here is the code..
var parent = function() {
var text = 'i can access the container';
return function() {
alert(text);
}
}();
parent();
Later i wanted returned an object instead of a function which have a method.This method is not directly in the body of the immediately-invoked-function rather it is defined inside the returned object.But it can access the variable called private which holds a string value.How come this variable is in the scope of this object literal method??
var parent = (function() {
var text = 'private variable';
return {
prop: 'i am the property',
method: function() {
alert('i can access ' + text);
}
}
})();
parent.method();
In JavaScript, Object literals don't create new scopes but only the functions do. So, all the variables declared in IIFE will be available to the method
function in the object literal.
The object literal can see anything that is defined in the block scope of the function its defined in.
This is what closures are for.
Your second example can be rewritten as:
var parent=(function(){
var text='private variable',
fnc = function(){
alert('i can access ' +text);
};
return {
prop:'i am the property',
method: fnc
}
})();
parent.method();
Or:
var text='private variable',
fnc = function(){
alert('i can access ' +text);
};
var parent=(function(){
return {
prop:'i am the property',
method: fnc
}
})();
parent.method();
And it's obvious that calling parent.method
or fnc
must give the same result.
来源:https://stackoverflow.com/questions/26447570/scope-of-the-object-literal-methods