you need to increase scope of you variable to window
object , than it will work.
In your current code scope of variable is limited to the function only. so you cannot access variable outside function.
something like will declare variable at larger scope, in below it declare variable at window object so it get accessible to all functions.
window.data = 1;
if you do like this than it is accessible in given window.
Globals are generally to be avoided. You should define variables within the scope of functions.
In your scenario in second case its working because data
is in scope of given function , and in first case data
is in scope of first function. that is reason it working in second case but not in first case.
in second case
function test1() {
var data = "from Test1";
var secondFunction1 = function() {
return function() {
console.log(data);
}()
}
secondFunction1();
}
if you see you secondFuction1
is able to get data because the scope is larger , both are part of test1()
.
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript. That means function inherits from object . Object instances can contain more instances which can be functions.
so if you go by above statement in OOD way, than in you case test1()
is object and in that object you have property called data
and function called secondFuction1()
, and in OOD function can access property of object , so that is reason its working in you second case.