0
votes

I have a holder object where I insert Class instances.

var instances = {};
$.each(response.data, function(index, value) {
    instances[value.platform.toLowerCase()] = new FetcherClass(value.platform, value.type, value.tempo, value.max);
});

value.platform is the name of the new instance.

All seems to works fine, but when I want to call a function within an instance, allways fires the function of the last instance.

For example:

instances.name1.start();

In case there are 'name1', 'name2' and 'name3' instances, the start() function fired belongs to 'name3' instance.

Here I post the output in console of Object 'instances'.

Object name1 : FetcherClass nam2 : FetcherClass name3 : FetcherClass name4 : FetcherClass name5 : FetcherClass name6 : FetcherClass name7 : FetcherClass name8 : FetcherClass name9 : FetcherClass name10 : FetcherClass proto : Object

A link to an example: JSFiddle

What's wrong?

2
Should there be a jQuery tag? - RobG
What are FetcherClass and start and response.data? - Oriol
response.data is an Array of Objects from server. FetcherClass is an Object which holds data & functions like start(). - Apalabrados
@Apalabrados You should include a minimal reproducible example - Oriol
@Oriol Here you are a link: jsfiddle.net/8048w4cc/1 - Apalabrados

2 Answers

2
votes

You have an accidental global variable in _self. The first time the constructor is called, a new global variable called _SELF was created; subsequent calls to the constructor replaced it, such that all instances of the object referred to the most recent one.

Declare a variable within the constructor for FetcherClass and use that instead.

    function FetcherClass(plataforma, type, interval, faults) {
        var SELF = this;
        SELF.PLATAFORMA = plataforma.toLowerCase();
        SELF.TYPE = type;
        SELF.INTERVAL = interval;
        SELF.MAX_INTENTOS = faults;

        SELF.start = function() {
            alert('I am '+SELF.PLATAFORMA);
        }
    }
0
votes

Your problem exists in the context of _self. If you use the variables directly, it works without an issues.

See JSFiddle