Я принял это от Google Code Playground http://code.google.com/apis/ajax/playground/Как получить доступ к переменным в закрытии, если есть локальные переменные с тем же именем?
/*CLOSURE
* When a function is defined in another function and it
* has access to the outer function's context even after
* the outer function returns
* An important concept to learn in Javascript
*/
function outerFunction(someNum) {
var someString = 'Hai!';
var content = document.getElementById('content');
function innerFunction() {
content.innerHTML = someNum + ': ' + someString;
content = null; // IE memory leak for DOM reference
}
innerFunction();
}
outerFunction(1);
///////////////////////
Ее все в порядке, но если у меня есть локальная переменная во внутренней функции с тем же именем переменной во внешней функции, то, как получить доступ к этой переменной?
function outerFunction(someNum) {
var someString = 'Hai!';
var content = document.getElementById('content');
function innerFunction() {
var someString='Hello';
content.innerHTML = someNum + ': ' + someString;
content = null; // IE memory leak for DOM reference
}
innerFunction();
}
outerFunction(1);
Почему бы не переименовать один из них? – kennytm
Я вставил строку var ss = someString; внутри внутренней функции. Тогда, когда я пытался получить доступ к ss, он возвращался undefined – Sriram
Очень похожее/дублирующее? Вопрос: http://stackoverflow.com/questions/1484143/scope-chain-in-javascript –