24 lines
1.3 KiB
Plaintext
24 lines
1.3 KiB
Plaintext
---
|
|
title: 'Difference between: `function Person(){}`, `var person = Person()`, and `var person = new Person()`?'
|
|
---
|
|
|
|
This question is pretty vague. Our best guess at its intention is that it is asking about constructors in JavaScript. 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.
|
|
|
|
`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 = 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)`.
|
|
|
|
```js
|
|
function Person(name) {
|
|
this.name = name;
|
|
}
|
|
|
|
var person = Person('John');
|
|
console.log(person); // undefined
|
|
console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined
|
|
|
|
var person = new Person('John');
|
|
console.log(person); // Person { name: "John" }
|
|
console.log(person.name); // "john"
|
|
```
|