Wednesday, September 23, 2015

JavaScript's new operator

In a previous post we explored the class-ical programming paradigm in JavaScript
The constructor pattern is a fundamental aspect of the class-ical paradigm
A constructor is code using which objects can be created from a class using the 'new' keyword
.
Under the hood, JavaScript uses it's prototypal mechanism to support this feature. In other posts I explore the prototypal form in depth. For now, lets try to understand how 'new' works:

Lets create a function Person to behave like a Java Class

1
2
3
4
5
function Person(first, last) {
  this.first = first;
  this.last = last;  
}
var s = new Person("Deepak", "Anand");

Here are the things that happened after the last line was executed:

  1. new creates a new object, lets call it this
  2. the (constructor) function Person is called like so: this.Person ("Deepak", "Anand")
  3. this is returned
Using upper-case for function-names that are used as constructors is convention only, not a language construct.

Now, what if you want methods in your "class"

Easy enough....

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function Person(first, last) {
  this.first = first;
  this.last = last;
  this.getFullName = function() {
    return this.first + ' ' + this.last;
  };
  this.getFullNameReversed = function() {
  return this.last + ', ' + this.first;
  };
}

This works, but is not very efficient. For every Person instance, 2 function objects are created.
The solution is to add methods to the function's prototype property like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function Person(first, last) {
  this.first = first;
  this.last = last;
}
Person.prototype.getFullName = function() {
  return this.first + ' ' + this.last;
};
Person.prototype.getFullNameReversed = function() {
  return this.last + ', ' + this.first;
};

References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript

No comments:

Post a Comment