Search code examples
javascriptscoping

scope of the object literal methods


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();

Solution

  • 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.