Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Scope in Injected Function

(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()?

like image 968
lilturtle Avatar asked Jul 21 '12 11:07

lilturtle


2 Answers

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.

like image 133
Ned Batchelder Avatar answered Oct 13 '22 09:10

Ned Batchelder


JavaScript has lexical scoping, not dynamic scoping (apart from this). See http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping

like image 24
1983 Avatar answered Oct 13 '22 09:10

1983