tags:

views:

338

answers:

2

A while ago I needed to create an object orientated class using jQuery. I turned to use John Resig's fine Class solution.

Hit an issue with it. When I define a global options object, it seems to me that the latter is shared amongst classes. I have confirmed that by printing various console.log's after modifying the object in one class only. 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 that i can easily pass optional settings to the class. Any way of doing it this way? I might have to resort to manual setters to the class if nothing works.

I am not too sure either why the options object is being statically shared across different class objects instantiated with the 'new' keyword.

+1  A: 

I may be wrong here, but try taking the "var" off of "var MyClass". Doing so will create "MyClass" in the window namespace, which in essence makes it global.


UPDATE

Is this 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 such as:

myObject.init();

or

myObject.setSpeed(100);

perhaps i dont understand the problem correctly and i should just stfu

p.s - the above code is straight from memory and not tested

I was a bit sceptical from your reply (since I didn't understand how making my class global will change the access rights of an internal variable to it), but indeed there was a change, and some values in my options array were unique. However, some other values have been carried over from the first class's internal values.
Hady
hady - javascript is actually a classless language. Perhaps, re-wording the problem and asking yourself the problem again may help. I just re-read your question and perhaps I misunderstood...
A: 

They are indeed sharing the options value, but that's because you assigned a modifed this.defaults and not a distinct object. From the jQuery.extend() docs:

Keep in mind that the target object will be modified, and will be returned from extend().

You can fix it by extending an empty object with the defaults and then options:

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