lilturtle
lilturtle

Reputation: 63

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

Upvotes: 6

Views: 166

Answers (2)

1983
1983

Reputation: 5963

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

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375734

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.

Upvotes: 4

Related Questions