I recommend Douglas Crockford's book to anyone who wants to learn more about JavaScript. It really consolidated my knowledge of the language. The book is short and enjoyable. The author comes off as really credible which is important as the book makes quite a few recommendations on proper usage and style. Here are a few notes that I took while reading the book.
The prototype chain
The prototype is only used when retrieving values. Setting a property always sets it on the receiver directly. To know if the receiver has a property without looking at the prototype, use #hasOwnProperty.
Function calls
Every function has access to two magic objects: this and arguments. This is a link to the current object and its value depends on the invocation pattern of the function. Arguments is an array-like object containing all the arguments passed in to the function.
There are four invocation patterns:
- As a method: when called on a receiver object, this represents the receiver
- As a function: when called without a receiver, the this pointer points to the global object
- As a constructor: when invoked with the new keyword, a new object is created using the function's prototype. This points to that new object.
- Using #apply: in this case, the this pointer is explicit and passed in to #apply.
Partial application in JavaScript
Here is a clever snippet from the book that allows function application.
Function.prototype.curry = function(){
var slice = Array.prototype.slice;
var args = slice.apply(arguments);
var that = this;
return function(){
return that.apply(null, args.concat(slice.apply(arguments)));
};
};You can then use it like this:
>>> function add(a,b) {return a + b;}
>>> add.curry(1)(2)
3
Recommendations and gotchas
- JavaScript does not have block scope
- Avoid the use of 'new'
- Always pass in the radix parameter to #parseInt
- Always use === and !==, not == or !=
- Avoid the use of 'with', use a local variable instead
- Avoid the use of 'void'
- Avoid the use of typed wrappers like new Boolean, new String, or new Number
- All characeters are 16-bits wide