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

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

this is a keyword not a variable. It has nothing to do with scope.
Gotcha. So no go on getting at that variable huh?
this is a reference to an object (or undefined), and it is resolved dynamically.
i think this is a keyword and everything to do with scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.