对象文字方法的范围 [英] scope of the object literal methods

查看:98
本文介绍了对象文字方法的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在做一些关于JS中的范围和提升的实验。我有两个例子让我以不同的方式让我感到困惑。首先,我已经为一个名为parent的变量分配了一个匿名函数。显然,返回的子函数可以访问它外部函数范围,因此它可以访问文本变量。它很简单。这是代码..

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

后来我想要返回一个对象而不是一个有方法的函数。这个方法不直接在直接调用函数的主体,而不是它在返回的对象内部定义。但是它可以访问名为private的变量,它保存一个字符串值。这个变量是否在这个对象文字方法的范围内?

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


推荐答案

在JavaScript中,对象文字不会创建新范围但只有函数。因此,在IIFE中声明的所有变量都可用于对象文字中的方法函数。

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.

这篇关于对象文字方法的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆