jcvegan
jcvegan

Reputation: 3170

Why can’t I declare variables in the middle of an object literal?

I'am doing somtehing like this

Client.Selectors = {
    var cfg = null;
    Init:function(config){
       ...
       cfg = config;
       ...
    },
    Close:function(){
    }
};

And on the debugger of chrome I got this error :

Uncaught SyntaxError: Unexpected identifier

I don't know why

Upvotes: 0

Views: 121

Answers (3)

Sarfraz
Sarfraz

Reputation: 382636

You have problem here:

var cfg = null;

Should be:

cfg : null,

Since you are using object literal notation. So = changed to : and ; changed to ,.

Client.Selectors = {
    cfg : null,
    Init:function(config){
       this.cfg = config;
    },
    Close:function(){
    }
};

Learn More:

Upvotes: 2

Jaime
Jaime

Reputation: 6814

You are declaring Selectors with the object literal notation and as such the syntax is

some = {
    identifier:value,
    id2:function() {}
}

and all the properties are accessible from the outside.... you may want to consider using a constructor function to encapsulate your cfg

some = function() {
   var privateVar = "something";

   return {
      init: function() {
         alert(privateVar);
      }
   }

}

Upvotes: 0

ironchefpython
ironchefpython

Reputation: 3409

var cfg = null;
Client.Selectors = {
    Init:function(config){
       ...
       cfg = config;
       ...
    },
    Close:function(){
    }
};

Upvotes: 3

Related Questions