Mohammed Nidhal
Mohammed Nidhal

Reputation: 62

What is difference between function within class constructor function and the method Inside class but outside constructor function (in js)?

What is difference between function within class constructor function and the method Inside class but outside constructor function (in js)?

I tried to search about this and did not find something understandable for me!

Thanks in advance!

  class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;

    /* this function within the constructor what is it’s difference
      from the method(1) below */

    withinFunction = function () { console.log(“This is rectangle”)};
  }
  
  // Method(1)
  calcArea() {
    return this.height * this.width;
  }
}

Upvotes: 1

Views: 72

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074158

In that specific example, the code is falling prey to what I call The Horror of Implicit Globals. withinFunction is a global variable (unless it's declared somewhere you haven't shown).

The more normal version is this:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;

    this.withinFunction = function () { console.log(“This is rectangle”)};
//  ^^^^^
  }
  
  // Method(1)
  calcArea() {
    return this.height * this.width;
  }
}

The difference is that withinFunction is created every time the constructor is called, and assigned as an "own" property on the object being created. In contrast, calcArea (defined using method syntax) is created once when the class construct is evaluated and put on the object that's assigned as the prototype of objects created via the constructor (Rectangle.prototype). So there's only one copy of calcArea that's shared by all instances, but withinFunction is created separately for each instance.

They both have their uses, particularly when withinFunction is created using arrow function syntax rather than traditional function syntax.

If you're using class syntax, in general it's best to prefer method syntax for the sharing aspect (though modern JavaScript engines are very efficient at having multiple function objects sharing the same code) and because it's easier to mock prototype functions for testing.

Upvotes: 3

Related Questions