I want to create a class in Javascript. This class should have
How this can be done ?
A good way to create objects that support public and private properties is to use a factory function:
function createObj(){
var privateVariable = "private";
var result = {};
result.publicProp = 12;
result.publicMethod = function() {
alert(this.publicProp);
alert(privateVariable);
};
//this will add properties dynamically to the object in question
result.createProperty = function (name, value) {
this[name] = value;
};
return result;
}
As for static, you can simulate them by putting them on the function itself
createObj.staticProperty1 = "sorta static";
And to see dynamic properties in action:
var obj = createObj();
obj.createProperty("foo", "bar");
alert(obj.foo); //alerts bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With