Henry
Henry

Reputation: 1065

how to access variables within the Objects

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.

Upvotes: 0

Views: 58

Answers (2)

airportyh
airportyh

Reputation: 22668

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)
   }

}

Upvotes: 0

user113716
user113716

Reputation: 322452

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.

Upvotes: 4

Related Questions