0

I'm creating an object with multiple functions.. i.e.:

var test = {

   setA: function(){
     console.log(a)
   }

   endB: function(){
     console.log(a)
   }

}

How do I declare variable a so that it can only be accessed in the test object and every function within that the object? and is there anything unique about accessing it than other variables?

I know I can declare a global variable but would rather avoid doing that.

2 Answers 2

4
var test = (function() {
    var a = 'test';
    return {

        setA: function(){ console.log(a) },  // <-- was missing a comma

        endB: function(){ console.log(a) }

    };
})();

This places a in a function invocation which creates a new variable environment. Only function inside this environment will be able to access it.

Your object that contains the functions is returned from the function, and assigned to test. Those two functions will continue to have access to a.

Example: http://jsfiddle.net/yWdFw/

This pattern:

(function() {

   // your code

})();

...is commonly called an immediately invoked function expression or IIFE. You're defining a function, and invoking it immediately. As such, its return value is what's being assigned to test.

Sign up to request clarification or add additional context in comments.

Comments

0

An alternative to patrick's answer is adding an attribute to the object and then accessing it via this

var test = {
   a: 'blah',

   setA: function(){
     console.log(this.a)
   },

   endB: function(){
     console.log(this.a)
   }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.