tôi mất này từ Google Code Sân chơi http://code.google.com/apis/ajax/playground/cách truy cập các biến trong đóng nếu có các biến cục bộ có cùng tên?
/*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);
///////////////////////
của nó tất cả ok, nhưng nếu tôi có một biến cục bộ trong hàm bên trong có cùng tên như là một biến trong chức năng bên ngoài sau đó làm thế nào để truy cập vào biến đó?
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);
Tại sao không đổi tên một trong số chúng? – kennytm
Tôi đã chèn một dòng var ss = someString; bên trong hàm bên trong. Sau đó, khi tôi cố gắng truy cập ss nó trở về không xác định – Sriram
Rất giống/trùng lặp? Câu hỏi: http://stackoverflow.com/questions/1484143/scope-chain-in-javascript –