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

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

    In your example blabla is a local variable, so it will go away when the constructor function ends.

    If you declare a function inside the constructor, which uses the variable, then the variable will be part of the closure for that function, and survives as long as the function (i.e. normally as long as the object):

    function Foo() {
      this.bla = 1;
      var blabla = 10;
    
      this.getBlabla = function() {
        alert(blabla); // still here
      }
    }
    

提交回复
热议问题