0

I have JavaScript code as below;

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 ? Could you please corelate how just "returning" the vars/methods makes them as public ?

Thank you.

1
  • You're not making the declared variable a public. You're returning an object with a property of the same name, and you've set it to the same value. When you changeVar, you're changing the property, not the original variable. Commented Feb 27, 2013 at 17:57

2 Answers 2

1

The value of the variable foo is actually the value returned by this function. 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;
        }
    }
})();
Sign up to request clarification or add additional context in comments.

Comments

0

Okay, you've returned an object in the anonymous function, which means that the object is assigned to 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. Can't help much without a more specific question.

2 Comments

Thx a lot...COuld you please clarify on the 2nd part...when u say "but you can continue to let the private variables exist, within the function's scope"
Could you please see the above question ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.