简体   繁体   English

Javascript公共变量/方法

[英]Javascript public variable/methods

I have JavaScript code as below; 我有如下的JavaScript代码;

var foo = (function() {
    //Private vars
    var a = 1;

    return {
        //Public vars/methods
        a: a,
        changeVar: function () {
            a = 2;
        }
    }
})();

Now I am not sure how the syntax for public vars/methods works ? 现在我不确定public vars / methods的语法如何工作? Could you please corelate how just "returning" the vars/methods makes them as public ? 您能否概括一下“返回”变量/方法如何使其公开?

Thank you. 谢谢。

The value of the variable foo is actually the value returned by this function. 变量foo的值实际上是此函数返回的值。 Notice on the last line, the () , indicating that this function is evaluated immediately. 请注意,在最后一行()表示此函数将立即求值。 By evaluating a function and assigning its return value to a variable, you are able to hide variables inside a local (function) scope, such that they are not accessible outside that scope. 通过评估函数并将其返回值分配给变量,您可以将变量隐藏在本地(函数)作用域内,以使在该作用域之外无法访问它们。 Only members on the returned object are accessible, but because any functions inside form a closure with their outer scope, you can still use local (hidden) variables. 只有返回对象上的成员才可访问,但是由于内部的任何函数都使用其外部作用域形成闭包,因此您仍然可以使用局部(隐藏)变量。

An example of this would be to hide some local state and only allow access to it through a method: 一个例子是隐藏一些本地状态,只允许通过一种方法访问它:

var foo = (function() {
    //Private vars
    var a = 1;

    return {
        //Public methods
        getVar: function () {
            return a;
        },
        setVar: function (val) {
            a = val;
        }
    }
})();

Okay, you've returned an object in the anonymous function, which means that the object is assigned to foo . 好的,您已经在匿名函数中返回了一个对象,这意味着该对象已分配给foo So you can access the object's properties like foo.a or foo.changeVar , but you can continue to let the private variables exist, within the function's scope. 因此,您可以访问对象的属性,例如foo.afoo.changeVar ,但是您可以继续让私有变量存在于函数范围内。 Can't help much without a more specific question. 没有一个更具体的问题就无济于事。

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

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