-2

I tried with 2 scenarios , In one I could access data variable and other couldn't. need clarification for clearing my scopes concept Scenario 1 : data not accessible

function test() {
  var data = "from Test";
  secondFunction();
}

function secondFunction() {
  return function() {
    console.log(data);
  }();
}

test();

Scenario 2: data is accessible

function test1() {
  var data = "from Test1";
  var secondFunction1 = function() {
    return function() {
      console.log(data);
    }()
  }
  secondFunction1();
}

test1();
Nitish Singla
  • 165
  • 1
  • 6
  • 2
    There are lots of tutorial for same. Also lots of good answers . – Ved Dec 06 '17 at 07:08
  • In your second case, you are creating a closure which remembers the value passed in at the time of creating it. In the first case, you are trying to access the variable which is local to `test()` function. – VPK Dec 06 '17 at 07:15
  • you can have look to my answer once , if you get information you are asking please do upvote/accept answer – Pranay Rana Dec 06 '17 at 07:21
  • let me know if you need more detail – Pranay Rana Dec 06 '17 at 09:22

1 Answers1

0

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.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263