This code results in "!" being logged on the 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 a this? Am I using this wrong? I don’t really understand what’s going on here.
I’d like for g.a() to continue returning the value of x defined in the first anonymous function.
I’m using node.js if it makes a difference.
In the immediate functions,
thisrefers to the global object [docs]. So in this case in both functionsthisindeed refers to the same element and you are overwritingxwith the second call.What object
thisrefers to is determined by how the function is called.funcName();, thenthisrefers to the global object.obj.funcName(),thisrefers to the object.newoperator,new funcName();,thisrefers to an empty object that inherits from the functions prototype.You can also explicitly set
thisby usingcall[docs] orapply[docs].Instead referring to
this, you could create a new object in both functions:Additional note: It makes no difference whether you run the code in the browser or with node.js. The global object is part of the specification and has to be provided by the execution environment. In browsers it is the
windowobject, I don’t what it is in node.js, but it does not matter as long as it follows the specification.