How to convert javascript object variable to class

How to define a class that I can install later?

I wrote myself a rotator class using jquery, which looks like this:

var Rotator = { Loop: null, init: function(identifierName) { ........ } } 

If I want to have one rotator on my page, that’s good. I just call Rotator.init() and am ready. However, when I want to have 3 rotators, I have to define 3 times all the class code, changing its name.

It would be easier if I could just do

  Instance1 = new rotator; Instance2 = new rotator; Instance3 = new rotator; 
+4
source share
2 answers

What follows is that your object literal may look like a reusable named function that can be created multiple times:

 var Rotator = function(name) { this.Name = name; this.Loop = null; this.init = function(identifierName) { this.Name = identifierName; }; }; // usage: var foorotator = new Rotator('foo'); var barrotator = new Rotator('bar'); alert(foorotator.Name); alert(barrotator.Name); 

http://jsfiddle.net/JzWCL/

After editing:

http://jsfiddle.net/mPzsq/

+3
source

The Xander solution looks like an acceptable form for a class object that is used only once. However, if you plan to subclass or multiply its instance, you should apply the methods to the prototype, and not define them in the functions of the main class (constructor). For instance:

 var Rotator = function(name) { //run your initialization logic inside this constructor function this.Name = name; this.Loop = null; } Rotator.prototype.someMethod = function() { //method code } var rotator1 = new Rotator('foo'); var rotator2 = new Rotator('bar'); 

The reason for using this structure is to prevent methods from being restored on every instance of the class. Applying the methods to the prototype, they will be shared by all instances of the class.

I found this to be a useful link for some basics of defining a JavaScript class: 3 ways to define a JavaScript class

+2
source

All Articles