5 ms·
What's the best way to handle variable scoping when using closures? How about when calling object methods from DOM events?
by darkxanthos 16y ago
What's the best way to handle variable scoping when using closures?
How about when calling object methods from DOM events?
- tantalor 16y agohttps://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind https://developer.mozilla.org/en/JavaScript/Reference/Global...
- geuis 16y agovar x = (function(){ var inner_foo = 1; //internal to closure return function(){ var foo = 'foo'; var bar = foo + inner_foo; //this function has access to variables from the outer scope. //inner_foo is still accessible console.log( inner_foo, foo, bar ); //1, 'foo', 'foo1' } })(); //Edit a couple minutes later: I'm realizing I may not be understanding exactly what you're asking for in the 2nd question. If you elaborate a bit... Since an event will execute either an assigned or anonymous function, the same rules towards variable scope in your closures still applies when the events execute. Having a function executed by a click event isn't fundamentally different than executing a function directly.
- tantalor 16y agoIt is when it's a function of an object.