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();,thisrefers global object. - if function assigned property of object,
obj.funcname(),thisrefers object. - if call function
newoperator,new funcname();,thisrefers 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
Post a Comment