javascript - How to access outer function variable in nested inner function in JS -
i new js , having doubt below example. please see inline comments.
function outer() { var x = 5; console.log("outer",x); // prints 5 console.log("-----------"); function inner() { var x = 6; console.log("inner",x); // prints 6 console.log("outer",x); // prints 6. how print 5 console.log("-----------"); function _inner() { var x = 7; console.log("_inner",x); // prints 7 console.log("inner",x); // prints 7. how print 6 console.log("outer",x); // prints 7. how print 5 console.log("-----------"); } _inner(); } inner(); } outer();
may helps you. assign variables nested functions because therefore clear varible should used have differ each other in way(name or via namespace):
function outer() { var x = 5; // or via namespace // var out = { x : 5 }; console.log("outer",x); // 5 console.log("-----------"); function inner() { inner.x = 6; console.log("inner",inner.x); // 6 console.log("outer",x); // 5 console.log("-----------"); function _inner() { _inner.x = 7; console.log("_inner",_inner.x); // 7 console.log("inner",inner.x); // 6 console.log("outer",x); // 5 // namespace // console.log("outer",out.x); // 5 console.log("-----------"); } _inner(); } inner(); } outer();
in example 2 of 3 varibles assign(not outer x) functions because otherwise assess outer.x outside outer function , assign value:
function outer(){ outer.x = 5; ... } // assign value outside outer function outer.x = 34;
but when local variable defined:
function outer(){ var x = 23; }
then there no chance assign local variable(x) value outside outer function.
Comments
Post a Comment