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"