Z
Z
zlodiak2018-01-29 07:38:32
JavaScript
zlodiak, 2018-01-29 07:38:32

How to apply the Prototype pattern correctly?

I'm trying to generate 20 objects of the same type using the Prototype generation pattern. But as a result I get 20 empty objects. This can be seen by displaying them in the console. Here is the code itself:

var stars = [],
    starsCnt = 20;
    
var Helper = function() {
  this.randomIntFromZero = function(maxExclusive) {
      return Math.floor(Math.random() * (maxExclusive));
  };              
};  

var helper = new Helper();

var starPrototype = {
  xCoord: helper.randomIntFromZero(400),
  yCoord: 0,
  color: helper.randomIntFromZero(5),
  speed: helper.randomIntFromZero(10)
};    

function star() {
  function F() {};  
  F.prototype = starPrototype;  
  return new F();  
};

for(var i = 0; i < starsCnt; i++) {    
  stars.push(new star());
}  

console.log(stars);

JSFIDDLE here .
The problem is that the console displays 20 empty objects (that is, each of them has no properties: xCoord, yCoord, color, speed)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question