Javascript scope in embedded 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 can I place whereAmI () in the same context as addFunc ()?

+6
source share
2 answers

Javascript is lexically limited: the name refers to variables based on where the name is defined, and not where the name is used. privateSomething considered as local in whereAmI and then in the global scope. He was not found in any of these places.

+4
source

JavaScript has lexical reach, not dynamic scaling (other than this ). See http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping

+2
source

Source: https://habr.com/ru/post/921022/


All Articles