(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()?
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.
JavaScript has lexical scoping, not dynamic scoping (apart from this
). See http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With