JavaScript: Accessing variable/property of middle/outer functions in nested functions

时间:2017-06-15 09:36:22

标签: javascript

I'm learning Javascript, and had this question. Here's some sample code:

var xq = false;
var fooyy = function ttt() {
  var xq = false;
  baryy = function() {
    var xq = true;
    console.log(xq);
    console.log(ttt);
    console.log(fooyy);
    console.log(ttt.xq);
    console.log(fooyy.xq);
    console.log(window.xq);
  }();
};

fooyy();
console.log(xq);
console.log(fooyy.xq);

Looking at the output, my question is, so does it mean that from an inner nested function, properties and variables of outer functions can't be accessed (both in the cases of having the same name and otherwise)? Or if they can, could you explain how and why? (I see that the local and global variables are accessible) Thanks!

2 个答案:

答案 0 :(得分:1)

does it mean that from an inner nested function, properties and variables of outer functions can't be accessed?

No. Those are not properties, they are variables. You tried to access them as properties of the functions, which don't exist.

I see that the local and global variables are accessible. What about variables of outer functions (both in the cases of having the same name and otherwise)?

They can be accessed as long as they have different names. This is known as lexical scope, and works even after the outer function has returned - the inner one will form a closure. You can access them simply by their name, they are local variables.

If you do however have a variable of the same name in your local scope, like in your example the variable xq, that local variable will shadow the variable from the outer scope and make it inaccessible. If you want to access it, you need to rename either variable.

答案 1 :(得分:0)

What you have there is a closure, nicely explained in this SO question.

Also, please have a look at this SO question, where people invested lots of effort to explain what a closure is.

In short, baryy function has access to outer variables.