Skip to content

Instantly share code, notes, and snippets.

@skinofstars
Last active December 14, 2015 03:59
Show Gist options
  • Save skinofstars/5024842 to your computer and use it in GitHub Desktop.
Save skinofstars/5024842 to your computer and use it in GitHub Desktop.
JS Patterns notes

cache array vars

for loops will calculate the comparison length every time, so...

for (var i = 0, max = foo.length; i < max; i++) {
  // do something
}

parseInt()

parseInt() assumes anything begining with a 0 is an octal. You can pass a second param to define base. parseInt("09", 10); // returns 9"

Constructors

A constructor will always return an object, and will return this if one is not explicitly returned.

var Person = function(name){
    this.name = name;
    this.sayName = function(){
        return "I'm " + this.name;
    }
}

var bob = new Person("Bob");
bob.sayName(); // retuns "I'm Bob"

If you don't use new then the this within the constructor function will refer to the global namspace. This is when you'll want to use var self = {} within the constructor and return that.

The problem here is that prototype properties are lost. You can fix this be self-invoking

function Person() {
    if (!(this instanceof Person)) {
        return new Person();
    }
}

functions

Just to get our terminology right:

function foo(){} // declaration (no semi-colon)
var foo = function(){}; // expression
var foo = function foo(){}; // named expression. note: non-standard this.name returns 'foo' 

bar(function(){...}); // also an expression, but passed as a param
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment