Cool Stuff About JavaScript

This “Javascript Language A to Z Cheat Sheet” is a very good read.

Callbacks

When creating your own library, it is often nice to give your users the ability to execute their own function at a predetermined time. This is done through a callback.

function libraryCode(userCallback) {

  //do regular stuff, and then…

  userCallback(); //execute their code

}

Closures

The power of a closure is in the fact that a variable (count, in this example) is kept alive even after the function has finished running (var bob = counter(2);). To create a closure, you need a function definition inside another function definition, and the inner function uses a variable in the outer function.

function counter(count) {
  console.log(">> setting count to " + count);
  return { //this object is the closure
    getCount: function() {
      return ++count;
    }
  };
};
var bob = counter(2);
console.log(bob.getCount()); //3
console.log(bob.getCount());​ //4

Notice that the inner closure object is referencing variable count outside of it.

Constructor Functions (Custom)

When a function is invoked with the keyword new, it is referred to as a Constructor function. The new means that the new object will have a hidden link to value of the function's prototype member and the this keyword will be bound to the new object.

function Pet(animal) {
  this.animal = animal;
}

var killer = new Pet('dog');
console.log(typeof killer); // "object"
console.log(killer.animal); // "dog"


var noNewObject = Pet();
console.log(typeof noNewObject); // "undefined"

The convention is that constructor functions should begin with a capital letter. Note: if the new keyword is not used, then the 'this' variable inside the function will refer to the global object. Can you smell a potential mess? Hence why the capital letter convention for constructor functions is used. The capital letter means: "I am a constructor function, please use the new keyword".