/, Web Development/Automagically returning objects

Automagically returning objects

In Javascript, all functions are objects:

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

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.

By |2018-01-24T15:20:24+00:00January 22nd, 2018|Javascript, Web Development|0 Comments

About the Author:

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.