node.js - specifics of closures in JavaScript and anonymous functions -


this code results in "!" being logged on console.

var g = {}; (function() {     var t = this;     t.x = "x";     g.a = function() {         console.log(t.x);     }; })();  (function() {     var t = this;     t.x = "!";     g.b = function() {         console.log(t.x);     }; })();  g.a(); 

do anonymous functions share this? using this wrong? don't understand what's going on here.

i'd g.a() continue returning value of x defined in first anonymous function.

i'm using node.js if makes difference.

in immediate functions, this refers global object [docs]. in case in both functions this indeed refers same element , overwriting x second call.

what object this refers determined how function called.

  • if execute function funcname();, this refers global object.
  • if function assigned property of object, obj.funcname() , this refers object.
  • if call function new operator, new funcname();, this refers empty object inherits functions prototype.

you can explicitly set this using call [docs] or apply [docs].


instead referring this, create new object in both functions:

var t = {}; 

additional note: makes no difference whether run code in browser or node.js. global object part of specification , has provided execution environment. in browsers window object, don't in node.js, not matter long follows specification.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -