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

后端 未结 7 1037
忘掉有多难
忘掉有多难 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:14

    Variables declared with var inside a function used as a constructor will, like all other variables declared with var inside any function, be visible only during the execution of that function (unless the value is closed over using closures).

    In other words, blabla is effectively invisible outside the function:

    var foo = new Foo();
    console.log(foo.bla);     // 1
    console.log(foo.blabla);  // throws NameError
    

    By defining functions which close over these variables, they become the closest thing JavaScript has to "private" variables:

    function Foo() {
        this.bla = 1;
        var private = 1;
    
        this.increment = function() {
            ++private;
        }
    
        this.getPrivateValue = function() {
            return private;
        }
    }
    
    foo = new Foo();
    console.log(foo.bla);                // 1
    foo.bla = 6;                         // legal
    console.log(foo.bla);                // 6
    console.log(foo.getPrivateValue());  // 1
    // console.log(foo.private);         // would throw an error
    foo.increment();                     // legal
    console.log(foo.getPrivateValue());  // 2
    // foo.getPrivateValue() = 5;        // syntax error. Still can't reassign to private no matter what you try!
    
    0 讨论(0)
提交回复
热议问题