Automagically returning objects

In Javascript, all functions are objects:

function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
console.log(this);
}

Constructors (shown below) make use of the ‘new’ operator and the ‘this’ variable to create empty objects. When the ‘new’ operator is used to construct an object, the function is invoked and an empty object is automagically returned.

var taylor = new Person()
console.log(taylor) // Person {}

The constructor invokes the function and will return an empty object unless. If you wish to do so, you can pass parameters when constructing a new empty object like so:

var bob = new Person('Bob', 'Smith')
console.log(bob) // Person {firstname: 'Bob', lastname: 'Smith'}

Each time you construct a new object, The ‘this’ variable now points to a new empty object in memory. You can then set the parameters passed into the function to properties of the ‘this’ variable using dot notation i.e this.firstname.

Leave a Reply

Your email address will not be published. Required fields are marked *