Bada
Bada's Coding

Bada's Coding

Constructors Don't Construct Instances When They Return Objects

Bada's photo
Bada
·Aug 28, 2022·

1 min read

Please look at the examples below.

I checked these in Chrome, Node.js and Firefox.

When the Constructor Doesn't Return an Object

function Person(name, age) {
  this.name = name;
  let _age = age;
  return _age;
}

console.log(new Person('Bada', 29));
// Person { name: 'Bada' }

The constructor does not return what it returns (_age) and makes an instance.

When the Constructor Returns an Object

function Person(name, age) {
  this.name = name;
  return { age: age };
}

console.log(new Person('Bada', 29));
// { age: 29 }

The constructor does not make the instance and returns what it returns ({ age: 29 }).

 
Share this