2

I have one question is local variable stay in memory in javascript ?.

if NOT

then from where this.getSecond function get second variable value ?

function ClassA(){
this.first ='test';
var second ='abc';
this.getSecond =function(){
return second
}

}

var a =new ClassA();
alert(a.getSecond())

if YES

where local variable store ?

fiddle link https://jsfiddle.net/pmwu742d/

user2182349
  • 9,569
  • 3
  • 29
  • 41
user944513
  • 12,247
  • 49
  • 168
  • 318

1 Answers1

1

To answer your question I want you to look at the code below. It is an example of the function nested into another function. Here we have 3 different scopes: global, newSaga and anonymous function's scope. But each time you call newSaga() function it pushes this anonymous function into the sagas array so that we can call it. Moreover, we can do it from the global scope.

To put it short, the answer it YES, they are stored inside the memory and you have them stored inside different in-memory-scopes (closures) so that they cannot be accessed from the scope that is above unless some trick was used to access them. But it only happens in the case where they are still in use like in your code or the code below. If there is no way you can access them - they are gone.

var sagas = [];
var hero = aHero(); // abstract function that randomly generates a HERO charachter 
var newSaga = function() {
  var foil = aFoil(); // abstract function that randomly generates a FOIL charachter 
  sagas.push(function() {
    var deed = aDeed(); // abstract function that randomly generates a DEED charachter 
    console.log(hero + deed + foil);
  });
};

// we only have an empty array SAGAS, HERO and a declared but not yet usen NEWSAGA function

newSaga(); // when you run this function it will generate a new "block" inside memory where it will store local variables. Especially FOIL 

// at this point FOIL will be generated and stored inside the memory

// then function will be pushed into the SAGAS array 
// NOTICE THAT THIS PUSHED FUNCTION WILL HAVE AN ACCES TO THE LOCAL VARIABLES OF THE NEWSAGA FUNCTION

sagas[0](); // so when you run this line of code it will randomly create a DEED charachter and console.log a message using global HERO variable + FOIL variable from the inside of newSaga() + DEED vatiable from inside itself

sagas[0](); // if you'd call it again HERO and FOIL wouldn't change which means that those variables WERE stored and your function has an access to the in-memory-scope where they've been actually stored. DEED will change because function we've pushed into SAGAS array generates new DEED each time it's called