laggingreflex
laggingreflex

Reputation: 34677

Setting a prototype property of an undeclared {object} inside an [array]

I have an array

var Nest = [];

And I plan on filling it with objects like this

bird_id1 = /*gotten from some outer variable, say*/ 8;
bird_id2 =  9;
bird1 = Nest[bird_id1] = { id: bird_id1, ... }
bird2 = Nest[bird_id2] = { id: bird_id2, ... }

Now I was wondering if I could have the bird, or = Nest[bird_idX] have a predefined function set though prototype, such that I can call it like

bird1.chirp(this.id);

or

Nest[bird_id2].chirp(this.id);

So essentially the chirp() function has to be defined as a protptype on the {Nest[]} object (which is inside an array). How could that be done?

I would try the regular method of defining the prototype property

Nest[?].prototype = function chirp(){...}

But I'm not sure how

Upvotes: 0

Views: 77

Answers (3)

Tibos
Tibos

Reputation: 27843

You can create the birds with a constructor:

// constructor
function Bird(id) {
  this.id = id;
}

// properties shared by all birds
Bird.prototype.chirp = function() {
  console.log('My id is: ' + this.id);
}

// nest
var Nest = [];
// ids
var bird_id_1 = 8, bird_id_2 = 9;

// create birds
Nest[bird_id_1] = new Bird(bird_id_1);
Nest[bird_id_2] = new Bird(bird_id_2);

// make them sing
Nest.forEach(function(bird){ bird.chirp(); });

Notice that while each bird has the same chirp method, the method doesn't need the id parameter to display different things. It simply acts on the data of the bird, in this case logging the id of the bird it was called on.

Upvotes: 1

KooiInc
KooiInc

Reputation: 122966

You can create a Bird constructor:

function Bird(id) {
 this.id = id;
}
Bird.prototype.chirp = function () { /*chirpchirp*/ }
// subsequently
bird_id1 = /*gotten from some outer variable, say*/ 8;
bird_id2 =  9;
bird1 = Nest[bird_id1] = new Bird(bird_id1);
bird2 = Nest[bird_id2] = new Bird(bird_id2);

Upvotes: 1

Stefano Ortisi
Stefano Ortisi

Reputation: 5336

The best approach would be create an Object Bird with that function in its prototype, and then use this object instances to fill your array:

var Bird = function(){};
Bird.prototype.chirp = function(id){};

var bird_id =  9;
bird1 = new Bird();
bird1.id = bird_id;

var Nest = [];
Nest[ bird_id ] = bird1;

And then you can easily use your chirp function:

Nest[ bird_id ].chirp();

Upvotes: 2

Related Questions