Hello, my name is: Amy

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

function Person(name) {
  this.name = 'Amy';
}

The above is what is considered a constructor function. Typically, these functions have a capital first letter. This function is used with new in order to create a new instance of the Person object:

var personAmy = new Person('Amy');

console.log(personAmy); // -->
    // Person {
    //   "name": "Amy"
    // }

In the above, a new object has been created using the Person constructor. personAmy would be considered an instanceof Person (personAmy instanceof Person === true).

Now for the last item:

var personMatt = Person('Matt');

In this example, it appears as if a new instance of Person is being created in the variable personMatt; however, note that there is no new.

Without new, the value of this is actually equal to the global object. So, if you are using strict mode, nothing will happen (because strict mode doesn't allow for this to be assigned to the global object). If you aren't using strict mode, then the global object will not have a property name of Matt.

var personMatt = Person('Matt'); 

console.log(name); // --> 'Matt'

So... Always call constructors with new!

Comments