JavaScript Quirks Reference

<rant>I’m tired of programming languages. Maybe I’ve been around too long. The “new” ones feel so “too little, too late” to me. Never liked being a “language lawyer”, though, regrettably, I get to be one when I’m teaching.</rant>

Here’s some JavaScript quirks I’d rather forget about, but, nu, need.


  1. Context?
    var o = {
    	method: function() {
    		alert(this === o);
    o.method(); // true
  2. Outside of context(?!), ie in the global scope, a function’s this refers to the global object, viz window(?):
    function foo() {
    	alert(this === window);
    foo(); // true
  3. call() executes a function as if it were a method of another object. The first parameter becomes this inside the method, and subsequent parameters are passed as arguments to the function.
    function foo() {
    	alert(this === window);
    foo(); // true; // false
  4. ECMA-262 (3rd edition):

    If thisArg is null or undefined, the called function is passed the global object as the this value. Otherwise, the called function is passed ToObject(thisArg) as the this value.

  5. apply()


  1. Declarations hoisted, but initializations aren’t.
    if (! ("x" in window)) {
    	var x = 1;
    alert(x); // undefined

    Thus, lint’s recommendation: single var, at top.


Encapsulation, namespaces, closures…

  1. function foo() {}; = function() {return this.baz;};
  2. (function() {


Built-in types, objects, functions



DOM manipulation

Comments are closed.