0

I need some light here please! I understand that everything that is inside the constructor function its called with the new keyword and initialized. so as shown in the snippet, below when I log the mycar instance, i can see the method declared inside the constructor but not the one declared in the body.

so the question are: 1)why im able to call succesfully the method defined in the body if is not among the propertys of the instance? 2) why at all I declare the methods in the body and not just inside the constructor? in the snipet below both are working

class car {
  constructor(_brand, _year, _color) {
    this.brand = _brand;
    this.year = _year;
    this.color = _color;
    // a method defined inside the constructor--------------------------
    this.get_brand_color = function () {
      return this.brand + this.color;
    };
  }
   // a method defined in the body of the class-----------------------------
  get_brand_year() {
    return this.brand + this.year;
  }
}

mycar = new car("chevrolet ", 1997, "red");

console.log(mycar); 
// logs: car {brand: 'chevrolet ', year: 1997, color: 'red', get_brand_color: ƒ}
console.log(mycar.get_brand_year());
// logs:chevrolet 1997
console.log(mycar.get_brand_color());
// logs:chevrolet red
  • `get_brand_year() { return this.brand + this.year; }` is a named method and `this.get_brand_color = function () { return this.brand + this.color; };` is a property containing an anonymous function. One difference is the `name` property: https://jsfiddle.net/q1gx0w9a/ You could write `this.get_brand_color = function get_brand_color () { return this.brand + this.color; };` to to have a name in both cases. – jabaa Sep 26 '21 at 14:34
  • 1
    One is a [method](//developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Method_definitions), the other a `function`. One difference: a method is not a constructor. But the more important difference: methods in the class itself are part of the prototype; `this.x =`…`;` in the constructor becomes part of the instance, instead. `new car().get_brand_year === new car().get_brand_year`, but `new car().get_brand_color !== new car().get_brand_color`. You normally don’t want to create new functions with every single instance. – Sebastian Simon Sep 26 '21 at 14:37
  • 1
    For clarification: the name property and ability to be called as a constructor do not come from the position of the function, but from the function creation itself. `this.get_brand_color = { get_brand_color(){ return this.brand + this.color; } }.get_brand_color;` would remove these two differences, i.e. a method like this now also cannot be constructed with `new` and it now has a `name`. But the _position_ determines function identity and prototype placement. – Sebastian Simon Sep 26 '21 at 14:47

0 Answers0