How to initialize an object in javascript?

I would like to initialize an object in javascript ..

My code is as follows:

var PageSlider = { sliders: [], addSlider: function(display, target, itemClass, width, height, itemsPerPage, defaultPage){ var slideConfig = { display : display, target : target }; var slider = this.createSlider(slideConfig); slider.initSlider(); this.sliders.push(slider); }, copy : function(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; }, getInstance : function(){ var copy = PageSlider.copy(PageSlider); this.sliders.length = 0; return copy; } } 

Using the getInstance () method, just copy the object. I need to do to get an instance of an object.

Help me please. Thanks.

+4
source share
5 answers

I would recommend prototyping like the following

 var PageSlider = function() { this.sliders = []; } PageSlider.prototype.addSlider = function(display, target, itemClass, width, height, itemsPerPage, defaultPage){ var slideConfig = { display : display, target : target }; var slider = this.createSlider(slideConfig); slider.initSlider(); this.sliders.push(slider); } slider = new PageSlider(); 
+8
source

PageSlider is already an object. To get an instance outside of it, just use its name, for example:

 var giveMeAnInstanceOfPageSlider = PageSlider; 
+2
source

You can do it like this since PageSlider is already an object

var pageSlider = PageSlider

+2
source

How about var pageSlider = PageSlider . PageSlider already an object.

+1
source

The idea of ​​the code is that getInstance will copy the PageSlider object, actually initialize a new empty object using the values ​​of the existing PageSlider object - the equivalent of obtaining an instance of the object.

This code is strange because it blurs the line between β€œclasses” and objects in JavaScript (which is similar to what the Io programming language does), and is more true for the concept of object prototypes.

+1
source

All Articles