Are variables statically or dynamically “scoped” in javascript?

前端 未结 7 1926
無奈伤痛
無奈伤痛 2020-12-13 18:38

Or more specific to what I need:

If I call a function from within another function, is it going to pull the variable from within the calling function, or from the le

7条回答
  •  感动是毒
    2020-12-13 18:57

    Variables are statically scoped in JavaScript (dynamic scoping is really a pretty messy business: you can read more about it on Wikipedia).

    In your case though, you're using a global variable, so all functions will access that same variable. Matthew Flaschen's reply shows how you can change it so the second myVar is actually a different variable.

    This Page explains how to declare global vs. local variables in JavaScript, in case you're not too familiar with it. It's different from the way most scripting languages do it. (In summary: the "var" keyword makes a variable local if declared inside a function, otherwise the variable is global.)

提交回复
热议问题