The first bit of code is essentially trying to determine how the constructor function was called ...
in javascript, you can use a function to create an object in two ways:
function _(id) { this.someProperty = "stuff"; //Do more stuff to "this" return this; } //in this scenario, the "this" object will be the window object var myObject = _(id); console.log(window.someProperty); //outputs "stuff"; console.log(myObject.someProperty); //outputs "stuff"; //in this scenario, the "this" object is what get actually returned... var myObject = new _(id); console.log(window.someProperty); //outputs "undefined" console.log(myObject.someProperty); //outputs "stuff"
therefore check for
if (window === this) { return new _(id); }
just there to make sure you don't accidentally call the constructor without the new keyword. that would be bad, since any property that you assigned to the object would immediately be assigned to the window namespace ... which would be bad.
as for your second question, the author uses return this; at the end of each method as a free interface design template
This allows you to conveniently and beautifully process objects. a common example of this is jQuery where you can bind methods to a single object ...
$(".some-css-selector").click(function() { ... do something to the selected objects during the "click" event }).keyup(function() { ... do something to the same objects during the "keyup" event });
EDIT: A bit more additional information in response to W3Geek's comments below:
from Douglas Crockford's book "Javascript: The Good Parts" (reads completely well if you get into JS ... only like 70 pages, but each one is worth reading).
The Javascript new operator creates a new object that inherits from the prototype element of the operand, and then calls the operand, binding the new object to this . This gives the operand (which is better to be a constructor function) the ability to configure a new object before it returns to the requestor.
If you forget to use the βnew operatorβ, you will get a regular function call instead, and this is due to the global object, not the new object. This means that your function will clobbering global variables when it tries to initialize new members. This is very bad.
...
Constructors are functions that are intended to be used with the new prefix. The new prefix creates a new object based on the function prototype and associates this object with the functions implied by the this parameter. If you neglect the prefix new , a new object will not be created, and this will be bound to the global object. This is a serious mistake.