2016-12-19 4 views
1

私は1つの質問は、ローカル変数は、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()) 

YES

あればどこのローカル変数の店?私はあなたが以下のコードを見てみたいあなたの質問に答えるために

フィドルリンク https://jsfiddle.net/pmwu742d/

+0

'ローカル変数store' - メモリ –

+0

にそれがクロージャを作りますか? – user944513

+0

あなたのフィドルリンクは、実際のjsfiddleの例ではなく、jsfiddleへのリンクです。 – Draco18s

答えて

1

。これは、別の関数にネストされた関数の例です。ここでは、global、newSaga、および匿名関数のスコープの3つのスコープがあります。しかし、newSaga()関数を呼び出すたびに、この無名関数をsagas配列にプッシュして呼び出すことができます。さらに、私たちはグローバルな範囲からそれを行うことができます。

、短いそれはYES、それらはメモリ 内に格納されており、彼らはある範囲からアクセスすることはできませんように、あなたがインメモリー・スコープ(閉鎖) 異なる内にそれらを格納している答えを、それを置くために それらにアクセスするためにいくつかのトリックが使用されていない限り、しかし、それはあなたのコードや以下のコードのように、まだ使用されている場合、 の場合にのみ起こります。 にアクセスできる方法がない場合、それらはなくなっています。

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 
関連する問題