What's the benefit of this?

Hi All,

Hope ya’ll having a great day.

What is the benefit of using the first way of a function constructor over the second? If any at all?

class Person {

    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

const roms = new Person('Romson', 33);
const camper = new Person('Anonymous', 13);
const Person = function(name = 'Anonymous', age = 13) {
    this.name = name;
    this.age = age;
}

const roms = new Person('Romson' 33);
const camper = new Person();

Thanks Ya’ll

Edit: I’ve seen this in an online tut. Just wondering what’s the benefit of the first function constructor in the class.

ES6 vs ES5: click for Babel

1 Like

The benefit is if you always want the name to be ‘Anonymous’ when the function is called without specifying a value for name. Otherwise, every time you want to make the name Anonymous, you would have to pass it it like in the first example. It just simplifies the code logic and being able to leave the extra argument off. The key is you really should put the default parameters at the end, so you can call like:

const Person = function(age, name = 'Anonymous', location = 'Unknown') {
    this.name = name;
    this.age = age;
    this.location = location;
}

const roms = new Person(33);

// roms => Person { name: 'Anonymous', age: 33, location: 'Unknown' }
1 Like

What @RandellDawson says, but you have two things going on here (default parameters and class). If you mean the difference between an ES6 class & a function constructor, adding a new keyword to the language meant that some slight changes could be introduced to how things work (mainly to do with inheritence/subclassing):

For class, removes ability to make a common error:

# class Person {}
> const roms = Person('Romson', 33)
TypeError: Class constructor Person cannot be invoked without 'new'

For constructor function:

# function Person() {
> const roms = Person('Romson', 33)
undefined # it worked, no errors
> roms
undefined # nothing there though

for class, simpler definition of prototype methods (prototype methods being the main point of classes):

class Example {
  method1() {
    // do something
  }

  method2() {
    // do something
  }
}

For constructor function:

function Example() {};

Example.prototype.method1 = function () {
  // do something
}

Example.prototype.method2 = function () {
  // do something
}

Subclassing (eg a Cat class could be a subclass of Animal) works, under-the-hood, slightly differently. ES6 allows subclassing builtins (Error, Array, etc, which is not really fully possible pre-ES6):

class MyArray extends Array {
  constructor() {
    super()
  }

  myArrayMethod() {
    // do stuff
  }
}
1 Like