How to define a class in javascript

I want to create a class in Javascript. This class must have

  • private and public variables and functions.
  • static and dynamic variables and functions.

How can I do that?

+4
source share
1 answer

A good way to create objects that support public and private properties is to use the 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 statics, you can simulate them by putting them in the function itself

 createObj.staticProperty1 = "sorta static"; 

And to see the dynamic properties in action:

 var obj = createObj(); obj.createProperty("foo", "bar"); alert(obj.foo); //alerts bar 
+6
source

Source: https://habr.com/ru/post/1387422/


All Articles