-1

I had a class in my code and I declared a constructor inside it...


 constructor(rowNumber) {
   this._rows = this.init(rowNumber);
 }
 get lastRow() {
   return this._rows[this._rows.length - 1];
 }
 get rows() {
   return this._rows;
 }

 fact(n) {
   return (n > 1) ? this.fact(n - 1) * n : 1;
 }
 createRow(row) {
   var result = [];
   for (let i = 0; i <= row; i++) {
     result.push(this.fact(row) / this.fact(i) / this.fact(row - i));
   }
   return result;
 }
 init(rowNumber) {
   var result = [];
   for (let i = 0; i < rowNumber; i++) {
     result.push(this.createRow(i));
   }
   return result;
 }
}

export {Triangle}; 

I declared init() function at the end of my code and I used init() in the constructor... if the constructor runs at first and then init() function runs ... does it cause a problem?

  • I found a same question here - https://stackoverflow.com/questions/46474094/why-are-javascript-functions-within-classes-not-hoisted – dungmidside Jun 23 '20 at 08:11
  • @108 Not really the same, there it's about a missing `this.`. – deceze Jun 23 '20 at 08:12
  • @Fatemeh, there is no such thing Java like class in Javascript (in java class is a template, in javascirpt class in an object of `Function`). Everything is an object in Javascript. Every function/class you define is an object of `Function constructor`(). You can check like `YourClassName instanceof Function;` – intekhab Jun 23 '20 at 08:13
  • There's no reason why calling a method in the constructor should cause a problem, unless you do something to create a problem. Your code above is fine. – TKoL Jun 23 '20 at 08:15
  • @intekhab The implementation details differ between Java and Javascript, but there's still a *conceptual* thing like a class, and since ES5 even an explicit `class` keyword. In the end both Java and Javascript classes accomplish the same task, even if the details differ slightly. – deceze Jun 23 '20 at 08:20
  • @108 I don't think so ... I asked about running a constructor inside a class and that question that you mentioned is not about constructor ... if you gave me down vote please tell me why – Fatemeh Azizkhani Jun 23 '20 at 08:20

1 Answers1

1

Javascript is first creating a class. That'll be an object which contains all those functions on its prototype. You then sometime later instantiate that class with new, at which point constructor and init will be called. At that point it doesn't matter in which order they were written into the source code, since they've already been parsed and put onto the prototype from where they will be called.

deceze
  • 510,633
  • 85
  • 743
  • 889