How can I declare a private var inside a literal object? Becasuse I've this code:
var foo = {
self: null,
init: function() {
self = this;
self.doStuff();
},
doStuff: function() {
//stuff here
}
}
This works perfectly, but if I have some objects, the var "self" it will override.. apparently it's a global var.. and I cannot use the restricted word "var" inside this object..
How can I solve this, or make an NameSpace for each object?
Thanks!
How can I declare a private var inside a literal object? Becasuse I've this code:
var foo = {
self: null,
init: function() {
self = this;
self.doStuff();
},
doStuff: function() {
//stuff here
}
}
This works perfectly, but if I have some objects, the var "self" it will override.. apparently it's a global var.. and I cannot use the restricted word "var" inside this object..
How can I solve this, or make an NameSpace for each object?
Thanks!
self = this; self.doStuff()
instead of this.doStuff()
?
– user395760
Commented
Dec 6, 2011 at 15:40
You can create a function scope to hide the variable:
var foo = (function() {
var self = null
return {
init: ...,
doStuff: ...
};
})();
Though it is not clear what self
is supposed to do here, and how foo
is used.
You have to use this
:
init: function() {
this.self = this;
this.self.doStuff();
},
edit However, it's still a property of the "foo" object, and it's not super-clear where you're getting instances of "foo" from. In other words, the way your code is written, there's only one object.
Alternatively, you could create your object with a closure:
var foo = function() {
var self = null;
return {
init: function() {
self = this;
self.doStuff();
},
doStuff: function() {
//stuff here
}
};
}();
You are not even using the property that you have created. Instead you create another global variable with the same name. Use the this
keyword to access properties:
var foo = {
self: null,
init: function() {
this.self = this;
this.self.doStuff();
},
doStuff: function() {
//stuff here
}
}
(Although saving this
in a property is truly pointless...)
If you want a local variable in the object, create a closure for it:
var foo = (function(){
var self = null;
return {
init: function() {
self = this;
self.doStuff();
},
doStuff: function() {
//stuff here
}
};
}());