是局部变量留在内存中的JavaScript?

时间:2016-12-19 03:02:36

标签: javascript

我有一个问题是局部变量在javascript中保留在内存中吗?

如果

然后从this.getSecond函数获取second变量值?

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

}

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

如果

本地变量存储在哪里?

小提琴链接 https://jsfiddle.net/pmwu742d/

1 个答案:

答案 0 :(得分:1)

要回答您的问题,我希望您查看下面的代码。它是嵌套到另一个函数中的函数的一个示例。这里我们有3个不同的范围:global,newSaga和匿名函数的范围。但是每次调用newSaga()函数时,它都会将这个匿名函数推送到sagas数组中,以便我们可以调用它。而且,我们可以从全球范围内做到这一点。

  

简而言之,答案是肯定的,它们存储在内存中   并且它们存储在不同的内存范围内(闭包)   这样就无法从上面的范围访问它们,除非   一些技巧被用来访问它们。但它只发生在这种情况下   它们仍在使用中,如代码或下面的代码。如果   你无法访问它们 - 它们已经消失了。

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