0

I have a use case as follows

var myObject1 = new myObject();

and myObject should have an array which will store all the objects created of this myObject

Example:-

if create an object such as

var xyz = new myObject();
myObject.all[0] == xyz

is there any way where - when I create an object & I can push it into an array which is in the definition of same object.

2
  • is there is any reason why the array must belong to myObject()? can't you just make a normal array and store the created objects there? Commented Mar 8, 2017 at 2:00
  • Make a singleton object that keeps track Commented Mar 8, 2017 at 2:00

2 Answers 2

4

You can create a property directly on the constructor function, to get the myObject.all[0] == xyz behaviour mentioned in the question. Add each object to the array from within the constructor:

function MyObject() {
  MyObject.all.push(this);
  // any other initialisation tasks here
}
MyObject.all = [];
    
var obj1 = new MyObject();
var obj2 = new MyObject();
    
// to access the array use MyObject.all:
console.log(MyObject.all[1] === obj2);  // true

Alternatively, you can add an array to the object prototype, but still add new objects to that array from within the constructor:

function MyObject() {
  this.all.push(this);
  // any other initialisation tasks here
}
MyObject.prototype.all = [];

var obj1 = new MyObject();
var obj2 = new MyObject();

// to access the array:
console.log(obj1.all);
// or
console.log(MyObject.prototype.all);

console.log(obj1.all[1] === obj2); // true

(Note: in both examples, I've spelled MyObject with a capital "M", because it is a JS convention for functions intended as constructors to be capitalised. This isn't mandatory.)

Sign up to request clarification or add additional context in comments.

3 Comments

Just beat me to it :) This is a case where prototypical inheritance really shines. You'd have to use a static property or outside singleton/global in traditional OOP
@CharlieMartin - Well JS does allow MyObject.all and that would work fine too. I've added it to my answer, because it seems to be more what the OP wanted.
Yeah I thought the prototype was a clever way to get the full list in each instance. Looking at the code, the static property is actually a little nicer. Should have known. Clever is rarely a good thing
0

Maybe something like this?

function MyObject(name){
   if (!O.prototype.instances) O.prototype.instances = [];
   O.prototype.instances.push(name);
}


var a = MyObject('a');
var b = MyObject('b');

console.log(MyObject.prototype.instances)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.