Sunday, May 12, 2013

The superpowers of constructors

2:37 AM Posted by Unknown No comments

Invoking a function as a constructor is a powerful feature of JavaScript, because when a constructor is invoked, the following special actions take place:
  • A new empty object is created.
  • This object is passed to the constructor as the this parameter, and thus becomes the constructor’s function context.
  • In the absence of any explicit return value, the new object is returned as the constructor’s value.

Scoping and functions

2:16 AM Posted by Unknown No comments

In JavaScript, scopes are declared by functions, and not by blocks. The scope of a declaration that’s created inside a block isn’t terminated (as it is in other languages) by the end of the block.

Consider the following code:


if (window) {
  var x = 213;
}
alert(x);


In most other languages, one would expect the scope of the declaration for x to terminate at the end of the block created by the if statement, and for the alert to fail with an undefined value. But if we were to run the preceding code in a page, the value 213 would be alerted because JavaScript doesn’t terminate scopes at the end of blocks.

That seems simple enough, but there are a few nuances to the scoping rules that depend upon what is being declared. Some of these nuances may come as a bit of a surprise:


  • Variable declarations are in scope from their point of declaration to the end of the function within which they’re declared, regardless of block nesting.
  • Named functions are in scope within the entire function within which they’re declared, regardless of block nesting. (Some call this mechanism hoisting.)
  • For the purposes of declaration scopes, the global context acts like one big function encompassing the code on the page.