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.
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
An anonymous function is just a function that has no name; nothing more. A closure is a function that captures the state of the surrounding environment. An anonymous function does not necessarily need to create a closure, and a closure is not created only for anonymous functions.
Difference between Function and ClosureFunction is declared using func keyword whereas Closure doesn't have func keyword. Function has always name but Closure doesn't have. Function doesn't have in keyword but closure has in the keyword.
Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
In the immediate functions, this
refers to the global object [docs]. So in this case in both functions this
indeed refers to the same element and you are overwriting x
with the second call.
What object this
refers to is determined by how the function is called.
funcName();
, then this
refers to the global object. obj.funcName()
, this
refers to the object. new
operator, new funcName();
, this
refers to an empty object that inherits from the functions prototype.You can also explicitly set this
by using call
[docs] or apply
[docs].
Instead referring to this
, you could create a new object in both functions:
var t = {};
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 window
object, I don't what it is in node.js, but it does not matter as long as it follows the specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With