What happens with “var” variables inside a JavaScript Constructor?

后端 未结 7 1092
忘掉有多难
忘掉有多难 2020-12-24 14:49

example:

function Foo() {
    this.bla = 1;
    var blabla = 10;
    blablabla = 100;
    this.getBlabla = function () { 
        return blabla; // exposes b         


        
7条回答
  •  感情败类
    2020-12-24 15:08

    If you don't use the var keyword, "blabla" becomes a global variable. At other points in the code if you also use blabla without var, it will also be global, and you can accidentally change other instances of blabla and introduce unintended bugs in your code. "var" puts the variable in the current scope, so in the case above, it's only accessible to Foo.

提交回复
热议问题