scope of the object literal methods

余生长醉 提交于 2019-12-06 17:28:19

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.

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