ewa
ewa

Reputation: 429

Javascript object / array question?

I am new to the javascript object model (prototype based) and am trying to do the following:

I have a constructor that simply initializes an array: this.myArray = []. I have a method:

MyConstructor.prototype.addToArray = function(myObject, type) {
   //
};

Basically I need myArray to be attached to a specific type. I.e. when addToArray() is called, the object will be added to an array associated with the type. I don't want to have to know all the possible types ahead of time. I also will need to add methods that clear the array holding objects of a certain type. So basically, I think I need to somehow create arrays dynamically which are associated with a type.

Any help would be appreciated.

I think my question is confusing so I'll try to elaborate: my "business" code creates objects which I need to keep track of. Each objects is associated with a certain "type" or "flavor". I am trying to make a generic object which handles storing these object references in arrays (an array per type) and handling operations on these objects. Operations then could be performed on all objects of a given type. I want to be able to do this without knowing the types ahead of time (i.e. avoid creating 1 array per type in the constructor).

"Type" could be anything. i.e. a string "typeA", or "typeB" etc. just a way of differentating between different classes of objects.

Upvotes: 0

Views: 397

Answers (2)

Russ Cam
Russ Cam

Reputation: 125488

If I've interpreted your question correctly, it's not possible to do what you want as JavaScript arrays are not typed - You can put any type of object in any array.

EDIT:

In light of your update, it sounds like you could have an object that has properties that match your object constructor names. Each property contains an array that holds objects created with a constructor that matches the property name.

For example,

function Cache() {}

Cache.prototype.add = function (obj) {
this[obj.constructor.name] === undefined? this[obj.constructor.name] = [obj] :
this[obj.constructor.name].push(obj);
}

function Constructor1(name, age) {
    this.name = name;
    this.age = age;
}

var cache = new Cache;
var con1 = new Constructor1('me', 10);
cache.add(con1);

console.log(cache) // has property 'Constructor1' containing an array with reference
                   // to object con1 in.

With this approach, you'll need to be careful and augment the constructor name when inheriting from objects.

Upvotes: 1

jtbandes
jtbandes

Reputation: 118681

You might do something like this:

var objects = {};
...
if (objects[type]) {
    objects[type].push(myObject);
} else {
    objects[type] = [myObject];
}
//...similar methods to delete objects, etc.

Upvotes: 1

Related Questions