scope of the object literal methods

。_饼干妹妹 提交于 2019-12-08 03:38:16

问题


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

回答1:


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.




回答2:


The object literal can see anything that is defined in the block scope of the function its defined in.




回答3:


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

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