Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an object in javascript?

Tags:

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. What i need to do is to get the instance of the object.

Help please. Thank you.

like image 844
newbie Avatar asked Jun 21 '12 22:06

newbie


4 Answers

PageSlider is an object already. So to get an instance outside of it, just use its name, like this:

var giveMeAnInstanceOfPageSlider = PageSlider;
like image 26
raina77ow Avatar answered Sep 27 '22 03:09

raina77ow


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

var pageSlider = PageSlider

like image 30
Jeff Robert Dagala Avatar answered Sep 26 '22 03:09

Jeff Robert Dagala


I would recommend prototyping, such as 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();
like image 115
Bryan Avatar answered Sep 24 '22 03:09

Bryan


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

like image 39
blockhead Avatar answered Sep 24 '22 03:09

blockhead