Javascript Scope in Injected Function

javascript, scope

Solution

Javascript is lexically scoped: a name refers to variables based on where the name is defined, not where the name is used. `privateSomething` is looked for as a local in `whereAmI`, and then in the global scope. It isn't found in either of those places.

Problem

``` (function(){ var privateSomething = "Boom!"; var fn = function(){} fn.addFunc = function(obj) { alert('Yeah i can do this: '+privateSomething); for(var i in obj) fn[i] = obj[i]; } window.fn=fn; })(); fn.addFunc({ whereAmI:function() { alert('Nope I\'ll get an error here: '+privateSomething); } }); fn.whereAmI(); ``` Why can't whereAmI() access privateSomething? and how do i place whereAmI() in the same context as addFunc()?

Original source