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

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

    It will become a local (think of 'private') variable within Foo(). Meaning that you can't access it outside of Foo().

    function Foo() {
      this.bla = 1; // this becomes an extension of Foo()
      var blabla = 10; // this becomes a "Local" (sort of like a 'private') variable
    }
    

    You could expose it (by returning it) with a Foo method.

    function Foo() {
        var blabla = 10; // local
    
        this.getBlabla = function () { 
            return blabla; // exposes blabla outside
        }
    }
    

    Now outside of Foo():

    var FooBar = new Foo();
    
    var what_is_blabla = FooBar.getBlabla(); //what_is_blabla will be 10
    

    jsFiddle demonstration

提交回复
热议问题