In JavaScript you can define function in a bunch of different ways:
function BatmanController () {
}
var BatmanController = function () {
}
// If you want to be EVIL
eval("function BatmanController () {}");
// If you are fancy
(function () {
function BatmanController () {
}
}());
By accident I ran across a unexpected behaviour today. When declaring a local variable (in the fancy way) with the same name as function the local variable takes presence inside the local scope. For example:
(function () {
"use strict";
function BatmanController () {
}
console.log(typeof BatmanController); // outputs "function"
var RobinController = function () {
}
console.log(typeof RobinController); // outputs "function"
var JokerController = 1;
function JokerController () {
}
console.log(typeof JokerController); // outputs "number", Ehm what?
}());
Anyone know why var JokerController isn’t overwritten by function JokerController? I tested this in Chrome, Safari, Canary, Firefox. I would guess it’s due to some “look ahead” JavaScript optimizing done in the V8 and JägerMonkey engines. But is there any technical explanation to explain this behaviour?
Because function and variable declarations are hoisted to the top of the scope in which they occur, yet assignments happen in place. Your code is effectively interpreted as this:
For the full technical details I suggest you read section 10.5 of the spec.