D
D
Daniil Popov2018-03-12 20:01:05
JavaScript
Daniil Popov, 2018-03-12 20:01:05

Why can't call the method?

I ran into a problem that I can't solve.
There is a constructor:

function Constructor(a, b, c){
  this.a = a;
  this.b = b;
  ...
}

There are methods for the constructor:
Constructor.prototype.method = function(){
  ...
}

There is a factory function that does not work as we would like:
function init(){
  var arr = [];

  for ... {
    arr.push(new Constructor(a, b, c));
  }

  arr.forEach(function(item){
    item.method();  // в этом месте ошибка TypeError: item.method is not a function
  }
}

The code is executed in "use strict" mode

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
twobomb, 2018-03-12
@twobomb

init()
Must be called after prototype description

E
eternalSt, 2018-03-13
@eternalSt

'use strict'

function Constructor(a, b, c){
  this.a = a;
};

Constructor.prototype.method = function(){
  console.log(`Run method: this.a: ${this.a}`);
};

function init(n){
  var arr = [];

  for(let i = 0; i < n; i++){
    arr.push(new Constructor(i));
  }

  arr.forEach(function(item){
    item.method();
  });
};

init(10);

Works as it should.
Although I must admit, I did not understand why there are two cycles?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question