简体   繁体   English

对象文字方法的范围

[英]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.. 我目前正在做一些关于JS的作用域和提升的实验。这里有两个示例,它们以不同的方式使我感到困惑:首先,我给一个名为parent的变量分配了一个匿名函数。显然返回的子函数可以访问其外部函数范围这样就可以访问文本变量。它很简单,很容易。这里是代码。

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?? 后来我想返回一个对象而不是一个有方法的函数。这个方法不是直接在立即调用函数的主体中而是在返回的对象中定义的,但是它可以访问名为private的变量,该变量包含一个字符串值。此变量为何在此对象文字方法的范围内?

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 . 在JavaScript中, 对象文字不会创建新的作用域,而仅会创建函数 So, all the variables declared in IIFE will be available to the method function in the object literal. 因此,IIFE中声明的所有变量将可用于对象常量中的method函数。

对象文字可以看到在其定义的功能的块范围内定义的任何内容。

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. 很明显,调用parent.methodfnc必须给出相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM