I want to define a single variable used among all instances in the Class definition(which is a plain function constructor in a jQuery plugin).
Is there such a feature?
If there is,just a simple demo and I think I'll understand.
I want to define a single variable used among all instances in the Class definition(which is a plain function constructor in a jQuery plugin).
Is there such a feature?
If there is,just a simple demo and I think I'll understand.
Your question is not very clear. Do you mean a global variable? A variable that can be accessed from any object?
EDIT (based on comments)
You can do something like this to make the variables scoped to just your code:
//This function will execute right away (it is basically the same as leaving it out,
//except that anything inside of it is scoped to it.
(function(){
var globalToThisScope = "this is global ONLY from within this code section";
window.object = {
//Now any instance of this object can see that variable,
// but anything outside of the outer empty function will not see anything
};
})();
Javascript doen't really provide that kind of data hiding, but this may suit your purposes:
function A()
{
if (!A.b) A.b = 1;//shared
//this.b = 0;//not shared
}
A.prototype.getB = function()
{
return A.b;//shared
//return this.b;//not shared
}
A.prototype.setB = function(value)
{
A.b = value;//shared
//this.b = value//not shared
}
function load()
{
var x = new A();
var y = new A();
y.setB(2);
document.body.innerHTML += x.getB();
}
output: 2
What you're looking for is essentially a private static
or protected static
variable, which can't be 100% emulated in javascript (that I know of).
You can make public static
or private
, though.
tehMick's solution gives you public static
with some convenience setters/getters, but it's really no different than if you replaced y.setB(2)
with A.b = 2
.
Here's how a private variable would work, but understand that this is still a per instance variable, and reflects the same value via the getter only because each instance sets it to the same literal string.
function SomeClass()
{
var privateVariable = 'foo';
this.publicVariable = 'bar';
this.getPrivateVariable = function()
{
return privateVariable;
}
this.setPrivateVariable = function( value )
{
privateVariable = value;
}
}
SomeClass.staticVariable = 'baz';
var a = new SomeClass();
var b = new SomeClass();
// Works...
alert( a.getPrivateVariable() );
alert( b.getPrivateVariable() );
// Until we try to set it...
a.setPrivateVariable( 'hello' );
// Then it breaks
alert( a.getPrivateVariable() );
alert( b.getPrivateVariable() );
I concur with Peter Bailey (+1). Douglas Crockford has a discussion of public and private instance variables; Peter suggests a nice way to add static public variables.