简体   繁体   中英

Why Closure property of javascript does not work with parent object

According to defination of closure in javascript: A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain.

Since everything is object in javascript even functions. My question is when comes to binding , the function (say bar)inside the object(say foo) can not access the properties of object directly. for eg:

   var foo= {
   tmp: 3,
   x:2,
  bar: function(y) {
    console.log(x + y + (++tmp)); 
  }

}

when execute

foo.bar(10)

it gives error that it cant recognize x & tmp.

But now when the above code is written this way

function foo(x) {
   tmp: 3,
   bar: function(y) {
    console.log(x + y + (++tmp)); 
    }
    bar(10);
  }

and then execute

foo(2);

it does not complain and gives output 16

I can understand that in second case it is able to access variables of parent functions because JavaScript has this property (we call it closure property).

But in the first case when the outer is actually a object , then the inner function can not access the variables of parent object( as it could access the variables of outer function) .

Although I know the workaround is to access the outer object variables with this keyword. But the question still remains.

Does not it violates the property of closure in first case??

Yes,as error shows the message x is not defined because in

var foo= {
   tmp: 3,
   x:2,
   bar: function(y) {
    console.log(x + y + (++tmp)); 
  }
}

as tmp and x are object of foo not the local variable of bar.And foo is parent of bar ,it can access by using this operator you can see it in below example.

var foo= {
    tmp: 3,
    x:2,
    bar: function(y) {
        console.log(this.x + y + (++this.tmp)); 
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM