gpt4 book ai didi

javascript - javascript中的局部变量是否保留在内存中?

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:59 25 4
gpt4 key购买 nike

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

如果

那么来自哪里this.getSecond函数获取second变量值?

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

}

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

如果

局部变量存储在哪里?

fiddle 链接 https://jsfiddle.net/pmwu742d/

最佳答案

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

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

关于javascript - javascript中的局部变量是否保留在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41215211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com