Wanna see something cool? Check out Angular Spotify 🎧
All Articles

Difference between: function Person(){}, var person = Person(), and var person = new Person()?

Technically speaking, function Person(){} is just a normal function declaration. The convention is to use PascalCase for functions that are intended to be used as constructors.

function Person(name) {
  this.name = name
}

var person = Person() invokes the Person as a function, and not as a constructor. Invoking as such is a common mistake if the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return undefined and that gets assigned to the variable intended as the instance.

var person = Person('John')
console.log(person) // undefined
console.log(person.name) // Uncaught TypeError: Cannot read property 'name' of undefined

var person = new Person() creates an instance of the Person object using the new operator, which inherits from Person.prototype. An alternative would be to use Object.create, such as: Object.create(Person.prototype).

var person = new Person('John')
console.log(person) // Person { name: "John" }
console.log(person.name) // "john"

Reference

Published 29 May 2021

Recent Posts

Warning: Can’t perform a React state update on an unmounted component

If you are a react developer, there is a good chance that you faced this warning at least once.

A simple Spotify client built with Angular 11, Nx workspace, ngrx, TailwindCSS and ng-zorro

An example of real-world monorepo codebase using Nx Workspace


Follow @tuantrungvo on Twitter for more!