An explanatin in a complicated function wich uses closures and ojbects

An explanatin in a complicated function wich uses closures and ojbects
0

#1

Hello,

I want an explanatin on the following javascript code

var a = (function(y,x) {
   var x = null;
   return {
     foo: function(x) {return this.bar(x*y);},
     bar: function(x){return x + y;}
   }
})(3,4);

console.log(a.foo(2));

Why does this code produces 9?
Thank you


#2

You call a.foo(2), so x inside foo is 2. y is 3, because that is what you pass to the anonymous function. So foo calls this.bar with x*y, which results in this.bar(6). bar just adds x (the parameter you pass to it) and y (still 3), resulting in 6 + 3 = 9.


#3

Fine explanation. Than you.