JQuery class statically pass object through class instances

A while ago I needed to create an object oriented class using jQuery. I turned to an excellent solution from the John Resig class .

To solve a problem. When I define the global options object, it seems to me that the latter is shared between classes. I confirmed this by printing out various console.log after changing an object in just one class. The code looks like this:

var MyClass = Class.extend({
    defaults : {
        distance : 10,
        speed : 20
    },
    options : null,

    init : function(options) {
        this.options = $.extend(this.defaults, options);
    },

    ...
});

      

I need a global hash or array so I can easily pass additional parameters to the class. Any way to do it this way? I may have to resort to manual installers in the class if all else fails.

I'm not too sure why the options object is statically shared between different class objects created with the new key.

+1


source to share


2 answers


I may be wrong, but try "var" from "var MyClass". This will create "MyClass" in the Windows namespace, which essentially makes it global.


UPDATE

This is what you need?

var myObject = function() {
    var defaults = {
                      speed: 20,
                      distance: 10
    };
    var options = null;
    return {
        init: function() { ... },
        setSpeed: function(speed) { this.defaults['speed'] = speed; },
        // etc
    }

}

      

and then call it like this:



myObject.init(); 

      

or

myObject.setSpeed(100);

      

Maybe I don't understand the problem correctly and I just need stfu

ps - the above code is straight from memory and untested

+1


source


They do use the value of options , but that's because you assigned the modified this.defaults , not a separate object. From the jQuery.extend () docs :

Be aware that the target will be modified and returned from extend ().



You can fix this by expanding an empty object with default settings and then parameters:

    this.options = $.extend({}, this.defaults, options);

      

0


source







All Articles