Skip to content Skip to sidebar Skip to footer

Functions In Global Context

I understand that functions called without the 'new' keyword spit out all their properties on to the global context. But I am seeing some curious behavior, with this piece of Javas

Solution 1:

Every time you call Test3, the inc, noInc and testRef functions are reassigned to window with a different a (which is initialized to 0 at the top of the function.)

window and o2 share the same a because the functions were reassigned to window when o2 got the return value and not o1.

Example from NodeJS REPL (note in NodeJS, the global object is referenced by global instead of window, but otherwise there shouldn't be any difference):

> function Test3() {
...  var a=0;......  this.inc = function() {...return ++a;...  };......  this.noInc = function() {...return a;...  };......  this.testRef = function() {...return this;...  };......return {...    inc: inc,...    testRef: testRef,...    noInc: noInc...  };...}
undefined
> var o = Test3();
undefined
> o.inc()
1
> o.inc()
2
> o.inc()
3
> noInc()
3

Because Test3 was only called once and set to o1, both the global scope and o1 share an a. Now watch as I call Test3 again:

> Test3()
{ inc: [Function],
  testRef: [Function],
  noInc: [Function] }
> noInc()
0
> o.noInc()
3

The functions are reassigned to the global object, with an a of 0, while o keeps the previous a.

Solution 2:

Your code can be reduced to:

var inc, noinc, a = 0, a2 = 0;
inc = function () {
   a += 1;
}
noinc = function () {
   return a;
}
inc();
inc();
inc();
noinc(); // 3

inc = function () {
   a2 += 1;
}
noinc = function () {
   return a2;
}
// now inc and noinc are bound to a2noinc(); // 0, yours gives 1?

So basically you're overriding the definition of inc and noinc bound to a different a.

If instead of var a = 0 you had this.a = this.a || 0 you would bind to the samea.

Post a Comment for "Functions In Global Context"