0

I have this code in Javascript:

function Camada(nome) {
  Camada.prototype.nome = nome;
  Camada.prototype.desenhar = function () {
  };
};

var camadas = [];

for (var i = 0; i < 10; i++) {
  var camada = new Camada('nome' + i);
  camadas[i] = camada;
}

for (var i = 0; i < 10; i++) {
  console.log(camadas[i]);
}

But this always prints 10 times the last object Camada, the problem looks like that camadas is keeping a reference to the var camada;

How can I solve this kind of problem using a for loop?

Irineu
  • 5
  • 3

4 Answers4

3

Issue with your code is that you're assigning to Camada.prototype in a constructor. Use this instead.

The difference is that assigning to prototype will make this property common among all the instances of Camada. Assigning to this will make it a property of the given instance only (which is what you want).

Difference between prototype and this is explained pretty well in this StackOverflow thread.

Try this:

function Camada(nome) {
    // Since you're using Camada as a constructor, you can use 'this'
    // and assign new objects properties to it.
    this.nome = nome;
    this.desenhar = function () {};
};

var camadas = [];

for (var i = 0; i < 10; i++) {
    var camada = new Camada('nome' + i);
    camadas[i] = camada;
}

for (var i = 0; i < 10; i++) {
    console.log(camadas[i].nome);
}
Community
  • 1
  • 1
kamituel
  • 34,606
  • 6
  • 81
  • 98
1

Because in the constructor for Camada you are changing the prototype. The prototype is like the class, and is shared by all Camadas.

This should be what you're after:

function Camada(nome) {
    this.nome = nome;
    this.desenhar = function () { };
};
Chris Charles
  • 4,406
  • 17
  • 31
0

You are passing your nome to the prototype. This means each time the constructor is called, it overwrites this property, and effects all instances.

Do not pass the nome value up to the prototype.

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
0

In the constructor you want to assign the param to the class property:

function Camada(nome) {
  this.nome = nome;
};
Angelo
  • 137
  • 1
  • 11