pass data from child to parent react, "this" advanced for me [duplicate] - reactjs

I am looking to find a clear explanation of what the "this" keyword does, and how to use it correctly.
It seems to behave strangely, and I don't fully understand why.
How does this work and when should it be used?

this is a keyword in JavaScript that is a property of an execution context. Its main use is in functions and constructors.
The rules for this are quite simple (if you stick to best practices).
Technical description of this in the specification
The ECMAScript standard defines this via the abstract operation (abbreviated AO) ResolveThisBinding:
The [AO] ResolveThisBinding […] determines the binding of the keyword this using the LexicalEnvironment of the running execution context. [Steps]:
Let envRec be GetThisEnvironment().
Return ? envRec.GetThisBinding().
Global Environment Records, module Environment Records, and function Environment Records each have their own GetThisBinding method.
The GetThisEnvironment AO finds the current running execution context’s LexicalEnvironment and finds the closest ascendant Environment Record (by iteratively accessing their [[OuterEnv]] properties) which has a this binding (i.e. HasThisBinding returns true). This process ends in one of the three Environment Record types.
The value of this often depends on whether code is in strict mode.
The return value of GetThisBinding reflects the value of this of the current execution context, so whenever a new execution context is established, this resolves to a distinct value. This can also happen when the current execution context is modified. The following subsections list the five cases where this can happen.
You can put the code samples in the AST explorer to follow along with specification details.
1. Global execution context in scripts
This is script code evaluated at the top level, e.g. directly inside a <script>:
<script>
// Global context
console.log(this); // Logs global object.
setTimeout(function(){
console.log("Not global context");
});
</script>
When in the initial global execution context of a script, evaluating this causes GetThisBinding to take the following steps:
The GetThisBinding concrete method of a global Environment Record envRec […] [does this]:
Return envRec.[[GlobalThisValue]].
The [[GlobalThisValue]] property of a global Environment Record is always set to the host-defined global object, which is reachable via globalThis (window on Web, global on Node.js; Docs on MDN). Follow the steps of InitializeHostDefinedRealm to learn how the [[GlobalThisValue]] property comes to be.
2. Global execution context in modules
Modules have been introduced in ECMAScript 2015.
This applies to modules, e.g. when directly inside a <script type="module">, as opposed to a simple <script>.
When in the initial global execution context of a module, evaluating this causes GetThisBinding to take the following steps:
The GetThisBinding concrete method of a module Environment Record […] [does this]:
Return undefined.
In modules, the value of this is always undefined in the global context. Modules are implicitly in strict mode.
3. Entering eval code
There are two kinds of eval calls: direct and indirect. This distinction exists since the ECMAScript 5th edition.
A direct eval call usually looks like eval(…); or (eval)(…); (or ((eval))(…);, etc.).1 It’s only direct if the call expression fits a narrow pattern.2
An indirect eval call involves calling the function reference eval in any other way. It could be eval?.(…), (…, eval)(…), window.eval(…), eval.call(…,…), etc. Given const aliasEval1 = eval; window.aliasEval2 = eval;, it would also be aliasEval1(…), aliasEval2(…). Separately, given const originalEval = eval; window.eval = (x) => originalEval(x);, calling eval(…) would also be indirect.
See chuckj’s answer to “(1, eval)('this') vs eval('this') in JavaScript?” and Dmitry Soshnikov’s ECMA-262-5 in detail – Chapter 2: Strict Mode (archived) for when you might use an indirect eval() call.
PerformEval executes the eval code. It creates a new declarative Environment Record as its LexicalEnvironment, which is where GetThisEnvironment gets the this value from.
Then, if this appears in eval code, the GetThisBinding method of the Environment Record found by GetThisEnvironment is called and its value returned.
And the created declarative Environment Record depends on whether the eval call was direct or indirect:
In a direct eval, it will be based on the current running execution context’s LexicalEnvironment.
In an indirect eval, it will be based on the [[GlobalEnv]] property (a global Environment Record) of the Realm Record which executed the indirect eval.
Which means:
In a direct eval, the this value doesn’t change; it’s taken from the lexical scope that called eval.
In an indirect eval, the this value is the global object (globalThis).
What about new Function? — new Function is similar to eval, but it doesn’t call the code immediately; it creates a function. A this binding doesn’t apply anywhere here, except when the function is called, which works normally, as explained in the next subsection.
4. Entering function code
Entering function code occurs when calling a function.
There are four categories of syntax to invoke a function.
The EvaluateCall AO is performed for these three:3
Normal function calls
Optional chaining calls
Tagged templates
And EvaluateNew is performed for this one:3
Constructor invocations
The actual function call happens at the Call AO, which is called with a thisValue determined from context; this argument is passed along in a long chain of call-related calls. Call calls the [[Call]] internal slot of the function. This calls PrepareForOrdinaryCall where a new function Environment Record is created:
A function Environment Record is a declarative Environment Record that is used to represent the top-level scope of a function and, if the function is not an ArrowFunction, provides a this binding. If a function is not an ArrowFunction function and references super, its function Environment Record also contains the state that is used to perform super method invocations from within the function.
In addition, there is the [[ThisValue]] field in a function Environment Record:
This is the this value used for this invocation of the function.
The NewFunctionEnvironment call also sets the function environment’s [[ThisBindingStatus]] property.
[[Call]] also calls OrdinaryCallBindThis, where the appropriate thisArgument is determined based on:
the original reference,
the kind of the function, and
whether or not the code is in strict mode.
Once determined, a final call to the BindThisValue method of the newly created function Environment Record actually sets the [[ThisValue]] field to the thisArgument.
Finally, this very field is where a function Environment Record’s GetThisBinding AO gets the value for this from:
The GetThisBinding concrete method of a function Environment Record envRec […] [does this]:
[…]
3. Return envRec.[[ThisValue]].
Again, how exactly the this value is determined depends on many factors; this was just a general overview. With this technical background, let’s examine all the concrete examples.
Arrow functions
When an arrow function is evaluated, the [[ThisMode]] internal slot of the function object is set to “lexical” in OrdinaryFunctionCreate.
At OrdinaryCallBindThis, which takes a function F:
Let thisMode be F.[[ThisMode]].
If thisMode is lexical, return NormalCompletion(undefined).
[…]
which just means that the rest of the algorithm which binds this is skipped. An arrow function does not bind its own this value.
So, what is this inside an arrow function, then? Looking back at ResolveThisBinding and GetThisEnvironment, the HasThisBinding method explicitly returns false.
The HasThisBinding concrete method of a function Environment Record envRec […] [does this]:
If envRec.[[ThisBindingStatus]] is lexical, return false; otherwise, return true.
So the outer environment is looked up instead, iteratively. The process will end in one of the three environments that have a this binding.
This just means that, in arrow function bodies, this comes from the lexical scope of the arrow function, or in other words (from Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?):
Arrow functions don’t have their own this […] binding. Instead, [this identifier is] resolved in the lexical scope like any other variable. That means that inside an arrow function, this [refers] to the [value of this] in the environment the arrow function is defined in (i.e. “outside” the arrow function).
Function properties
In normal functions (function, methods), this is determined by how the function is called.
This is where these “syntax variants” come in handy.
Consider this object containing a function:
const refObj = {
func: function(){
console.log(this);
}
};
Alternatively:
const refObj = {
func(){
console.log(this);
}
};
In any of the following function calls, the this value inside func will be refObj.1
refObj.func()
refObj["func"]()
refObj?.func()
refObj.func?.()
refObj.func``
If the called function is syntactically a property of a base object, then this base will be the “reference” of the call, which, in usual cases, will be the value of this. This is explained by the evaluation steps linked above; for example, in refObj.func() (or refObj["func"]()), the CallMemberExpression is the entire expression refObj.func(), which consists of the MemberExpression refObj.func and the Arguments ().
But also, refObj.func and refObj play three roles, each:
they’re both expressions,
they’re both references, and
they’re both values.
refObj.func as a value is the callable function object; the corresponding reference is used to determine the this binding.
The optional chaining and tagged template examples work very similarly: basically, the reference is everything before the ?.(), before the ``, or before the ().
EvaluateCall uses IsPropertyReference of that reference to determine if it is a property of an object, syntactically. It’s trying to get the [[Base]] property of the reference (which is e.g. refObj, when applied to refObj.func; or foo.bar when applied to foo.bar.baz). If it is written as a property, then GetThisValue will get this [[Base]] property and use it as the this value.
Note: Getters / Setters work the same way as methods, regarding this. Simple properties don’t affect the execution context, e.g. here, this is in global scope:
const o = {
a: 1,
b: this.a, // Is `globalThis.a`.
[this.a]: 2 // Refers to `globalThis.a`.
};
Calls without base reference, strict mode, and with
A call without a base reference is usually a function that isn’t called as a property. For example:
func(); // As opposed to `refObj.func();`.
This also happens when passing or assigning methods, or using the comma operator. This is where the difference between Reference Record and Value is relevant.
Note function j: following the specification, you will notice that j can only return the function object (Value) itself, but not a Reference Record. Therefore the base reference refObj is lost.
const g = (f) => f(); // No base ref.
const h = refObj.func;
const j = () => refObj.func;
g(refObj.func);
h(); // No base ref.
j()(); // No base ref.
(0, refObj.func)(); // Another common pattern to remove the base ref.
EvaluateCall calls Call with a thisValue of undefined here. This makes a difference in OrdinaryCallBindThis (F: the function object; thisArgument: the thisValue passed to Call):
Let thisMode be F.[[ThisMode]].
[…]
If thisMode is strict, let thisValue be thisArgument.
Else,
If thisArgument is undefined or null, then
Let globalEnv be calleeRealm.[[GlobalEnv]].
[…]
Let thisValue be globalEnv.[[GlobalThisValue]].
Else,
Let thisValue be ! ToObject(thisArgument).
NOTE: ToObject produces wrapper objects […].
[…]
Note: step 5 sets the actual value of this to the supplied thisArgument in strict mode — undefined in this case. In “sloppy mode”, an undefined or null thisArgument results in this being the global this value.
If IsPropertyReference returns false, then EvaluateCall takes these steps:
Let refEnv be ref.[[Base]].
Assert: refEnv is an Environment Record.
Let thisValue be refEnv.WithBaseObject().
This is where an undefined thisValue may come from: refEnv.WithBaseObject() is always undefined, except in with statements. In this case, thisValue will be the binding object.
There’s also Symbol.unscopables (Docs on MDN) to control the with binding behavior.
To summarize, so far:
function f1(){
console.log(this);
}
function f2(){
console.log(this);
}
function f3(){
console.log(this);
}
const o = {
f1,
f2,
[Symbol.unscopables]: {
f2: true
}
};
f1(); // Logs `globalThis`.
with(o){
f1(); // Logs `o`.
f2(); // `f2` is unscopable, so this logs `globalThis`.
f3(); // `f3` is not on `o`, so this logs `globalThis`.
}
and:
"use strict";
function f(){
console.log(this);
}
f(); // Logs `undefined`.
// `with` statements are not allowed in strict-mode code.
Note that when evaluating this, it doesn’t matter where a normal function is defined.
.call, .apply, .bind, thisArg, and primitives
Another consequence of step 5 of OrdinaryCallBindThis, in conjunction with step 6.2 (6.b in the spec), is that a primitive this value is coerced to an object only in “sloppy” mode.
To examine this, let’s introduce another source for the this value: the three methods that override the this binding:4
Function.prototype.apply(thisArg, argArray)
Function.prototype. {call, bind} (thisArg, ...args)
.bind creates a bound function, whose this binding is set to thisArg and cannot change again. .call and .apply call the function immediately, with the this binding set to thisArg.
.call and .apply map directly to Call, using the specified thisArg. .bind creates a bound function with BoundFunctionCreate. These have their own [[Call]] method which looks up the function object’s [[BoundThis]] internal slot.
Examples of setting a custom this value:
function f(){
console.log(this);
}
const myObj = {},
g = f.bind(myObj),
h = (m) => m();
// All of these log `myObj`.
g();
f.bind(myObj)();
f.call(myObj);
h(g);
For objects, this is the same in strict and non-strict mode.
Now, try to supply a primitive value:
function f(){
console.log(this);
}
const myString = "s",
g = f.bind(myString);
g(); // Logs `String { "s" }`.
f.call(myString); // Logs `String { "s" }`.
In non-strict mode, primitives are coerced to their object-wrapped form. It’s the same kind of object you get when calling Object("s") or new String("s"). In strict mode, you can use primitives:
"use strict";
function f(){
console.log(this);
}
const myString = "s",
g = f.bind(myString);
g(); // Logs `"s"`.
f.call(myString); // Logs `"s"`.
Libraries make use of these methods, e.g. jQuery sets the this to the DOM element selected here:
$("button").click(function(){
console.log(this); // Logs the clicked button.
});
Constructors, classes, and new
When calling a function as a constructor using the new operator, EvaluateNew calls Construct, which calls the [[Construct]] method. If the function is a base constructor (i.e. not a class extends…{…}), it sets thisArgument to a new object created from the constructor’s prototype. Properties set on this in the constructor will end up on the resulting instance object. this is implicitly returned, unless you explicitly return your own non-primitive value.
A class is a new way of creating constructor functions, introduced in ECMAScript 2015.
function Old(a){
this.p = a;
}
const o = new Old(1);
console.log(o); // Logs `Old { p: 1 }`.
class New{
constructor(a){
this.p = a;
}
}
const n = new New(1);
console.log(n); // Logs `New { p: 1 }`.
Class definitions are implicitly in strict mode:
class A{
m1(){
return this;
}
m2(){
const m1 = this.m1;
console.log(m1());
}
}
new A().m2(); // Logs `undefined`.
super
The exception to the behavior with new is class extends…{…}, as mentioned above. Derived classes do not immediately set their this value upon invocation; they only do so once the base class is reached through a series of super calls (happens implicitly without an own constructor). Using this before calling super is not allowed.
Calling super calls the super constructor with the this value of the lexical scope (the function Environment Record) of the call. GetThisValue has a special rule for super calls. It uses BindThisValue to set this to that Environment Record.
class DerivedNew extends New{
constructor(a, a2){
// Using `this` before `super` results in a ReferenceError.
super(a);
this.p2 = a2;
}
}
const n2 = new DerivedNew(1, 2);
console.log(n2); // Logs `DerivedNew { p: 1, p2: 2 }`.
5. Evaluating class fields
Instance fields and static fields were introduced in ECMAScript 2022.
When a class is evaluated, ClassDefinitionEvaluation is performed, modifying the running execution context. For each ClassElement:
if a field is static, then this refers to the class itself,
if a field is not static, then this refers to the instance.
Private fields (e.g. #x) and methods are added to a PrivateEnvironment.
Static blocks are currently a TC39 stage 3 proposal. Static blocks work the same as static fields and methods: this inside them refers to the class itself.
Note that in methods and getters / setters, this works just like in normal function properties.
class Demo{
a = this;
b(){
return this;
}
static c = this;
static d(){
return this;
}
// Getters, setters, private modifiers are also possible.
}
const demo = new Demo;
console.log(demo.a, demo.b()); // Both log `demo`.
console.log(Demo.c, Demo.d()); // Both log `Demo`.
1: (o.f)() is equivalent to o.f(); (f)() is equivalent to f(). This is explained in this 2ality article (archived). Particularly see how a ParenthesizedExpression is evaluated.
2: It must be a MemberExpression, must not be a property, must have a [[ReferencedName]] of exactly "eval", and must be the %eval% intrinsic object.
3: Whenever the specification says “Let ref be the result of evaluating X.”, then X is some expression that you need to find the evaluation steps for. For example, evaluating a MemberExpression or CallExpression is the result of one of these algorithms. Some of them result in a Reference Record.
4: There are also several other native and host methods that allow providing a this value, notably Array.prototype.map, Array.prototype.forEach, etc. that accept a thisArg as their second argument. Anyone can make their own methods to alter this like (func, thisArg) => func.bind(thisArg), (func, thisArg) => func.call(thisArg), etc. As always, MDN offers great documentation.
Just for fun, test your understanding with some examples
For each code snippet, answer the question: “What is the value of this at the marked line? Why?”.
To reveal the answers, click the gray boxes.
if(true){
console.log(this); // What is `this` here?
}
globalThis. The marked line is evaluated in the initial global execution context.
const obj = {};
function myFun(){
return { // What is `this` here?
"is obj": this === obj,
"is globalThis": this === globalThis
};
}
obj.method = myFun;
console.log(obj.method());
obj. When calling a function as a property of an object, it is called with the this binding set to the base of the reference obj.method, i.e. obj.
const obj = {
myMethod: function(){
return { // What is `this` here?
"is obj": this === obj,
"is globalThis": this === globalThis
};
}
},
myFun = obj.myMethod;
console.log(myFun());
globalThis. Since the function value myFun / obj.myMethod is not called off of an object, as a property, the this binding will be globalThis.
This is different from Python, in which accessing a method (obj.myMethod) creates a bound method object.
const obj = {
myFun: () => ({ // What is `this` here?
"is obj": this === obj,
"is globalThis": this === globalThis
})
};
console.log(obj.myFun());
globalThis. Arrow functions don’t create their own this binding. The lexical scope is the same as the initial global scope, so this is globalThis.
function myFun(){
console.log(this); // What is `this` here?
}
const obj = {
myMethod: function(){
eval("myFun()");
}
};
obj.myMethod();
globalThis. When evaluating the direct eval call, this is obj. However, in the eval code, myFun is not called off of an object, so the this binding is set to the global object.
function myFun() {
// What is `this` here?
return {
"is obj": this === obj,
"is globalThis": this === globalThis
};
}
const obj = {};
console.log(myFun.call(obj));
obj. The line myFun.call(obj); is invoking the special built-in function Function.prototype.call, which accepts thisArg as the first argument.
class MyCls{
arrow = () => ({ // What is `this` here?
"is MyCls": this === MyCls,
"is globalThis": this === globalThis,
"is instance": this instanceof MyCls
});
}
console.log(new MyCls().arrow());
It’s the instance of MyCls. Arrow functions don’t change the this binding, so it comes from lexical scope. Therefore, this is exactly the same as with the class fields mentioned above, like a = this;. Try changing it to static arrow. Do you get the result you expect?

The this keyword behaves differently in JavaScript compared to other languages. In Object Oriented languages, the this keyword refers to the current instance of the class. In JavaScript the value of this is determined by the invocation context of function (context.function()) and where it is called.
1. When used in global context
When you use this in global context, it is bound to global object (window in browser)
document.write(this); //[object Window]
When you use this inside a function defined in the global context, this is still bound to global object since the function is actually made a method of global context.
function f1()
{
return this;
}
document.write(f1()); //[object Window]
Above f1 is made a method of global object. Thus we can also call it on window object as follows:
function f()
{
return this;
}
document.write(window.f()); //[object Window]
2. When used inside object method
When you use this keyword inside an object method, this is bound to the "immediate" enclosing object.
var obj = {
name: "obj",
f: function () {
return this + ":" + this.name;
}
};
document.write(obj.f()); //[object Object]:obj
Above I have put the word immediate in double quotes. It is to make the point that if you nest the object inside another object, then this is bound to the immediate parent.
var obj = {
name: "obj1",
nestedobj: {
name:"nestedobj",
f: function () {
return this + ":" + this.name;
}
}
}
document.write(obj.nestedobj.f()); //[object Object]:nestedobj
Even if you add function explicitly to the object as a method, it still follows above rules, that is this still points to the immediate parent object.
var obj1 = {
name: "obj1",
}
function returnName() {
return this + ":" + this.name;
}
obj1.f = returnName; //add method to object
document.write(obj1.f()); //[object Object]:obj1
3. When invoking context-less function
When you use this inside function that is invoked without any context (i.e. not on any object), it is bound to the global object (window in browser)(even if the function is defined inside the object) .
var context = "global";
var obj = {
context: "object",
method: function () {
function f() {
var context = "function";
return this + ":" +this.context;
};
return f(); //invoked without context
}
};
document.write(obj.method()); //[object Window]:global
Trying it all with functions
We can try above points with functions too. However there are some differences.
Above we added members to objects using object literal notation. We can add members to functions by using this. to specify them.
Object literal notation creates an instance of object which we can use immediately. With function we may need to first create its instance using new operator.
Also in an object literal approach, we can explicitly add members to already defined object using dot operator. This gets added to the specific instance only. However I have added variable to the function prototype so that it gets reflected in all instances of the function.
Below I tried out all the things that we did with Object and this above, but by first creating function instead of directly writing an object.
/*********************************************************************
1. When you add variable to the function using this keyword, it
gets added to the function prototype, thus allowing all function
instances to have their own copy of the variables added.
*********************************************************************/
function functionDef()
{
this.name = "ObjDefinition";
this.getName = function(){
return this+":"+this.name;
}
}
obj1 = new functionDef();
document.write(obj1.getName() + "<br />"); //[object Object]:ObjDefinition
/*********************************************************************
2. Members explicitly added to the function protorype also behave
as above: all function instances have their own copy of the
variable added.
*********************************************************************/
functionDef.prototype.version = 1;
functionDef.prototype.getVersion = function(){
return "v"+this.version; //see how this.version refers to the
//version variable added through
//prototype
}
document.write(obj1.getVersion() + "<br />"); //v1
/*********************************************************************
3. Illustrating that the function variables added by both above
ways have their own copies across function instances
*********************************************************************/
functionDef.prototype.incrementVersion = function(){
this.version = this.version + 1;
}
var obj2 = new functionDef();
document.write(obj2.getVersion() + "<br />"); //v1
obj2.incrementVersion(); //incrementing version in obj2
//does not affect obj1 version
document.write(obj2.getVersion() + "<br />"); //v2
document.write(obj1.getVersion() + "<br />"); //v1
/*********************************************************************
4. `this` keyword refers to the immediate parent object. If you
nest the object through function prototype, then `this` inside
object refers to the nested object not the function instance
*********************************************************************/
functionDef.prototype.nestedObj = { name: 'nestedObj',
getName1 : function(){
return this+":"+this.name;
}
};
document.write(obj2.nestedObj.getName1() + "<br />"); //[object Object]:nestedObj
/*********************************************************************
5. If the method is on an object's prototype chain, `this` refers
to the object the method was called on, as if the method was on
the object.
*********************************************************************/
var ProtoObj = { fun: function () { return this.a } };
var obj3 = Object.create(ProtoObj); //creating an object setting ProtoObj
//as its prototype
obj3.a = 999; //adding instance member to obj3
document.write(obj3.fun()+"<br />");//999
//calling obj3.fun() makes
//ProtoObj.fun() to access obj3.a as
//if fun() is defined on obj3
4. When used inside constructor function.
When the function is used as a constructor (that is when it is called with new keyword), this inside function body points to the new object being constructed.
var myname = "global context";
function SimpleFun()
{
this.myname = "simple function";
}
var obj1 = new SimpleFun(); //adds myname to obj1
//1. `new` causes `this` inside the SimpleFun() to point to the
// object being constructed thus adding any member
// created inside SimipleFun() using this.membername to the
// object being constructed
//2. And by default `new` makes function to return newly
// constructed object if no explicit return value is specified
document.write(obj1.myname); //simple function
5. When used inside function defined on prototype chain
If the method is on an object's prototype chain, this inside such method refers to the object the method was called on, as if the method is defined on the object.
var ProtoObj = {
fun: function () {
return this.a;
}
};
//Object.create() creates object with ProtoObj as its
//prototype and assigns it to obj3, thus making fun()
//to be the method on its prototype chain
var obj3 = Object.create(ProtoObj);
obj3.a = 999;
document.write(obj3.fun()); //999
//Notice that fun() is defined on obj3's prototype but
//`this.a` inside fun() retrieves obj3.a
6. Inside call(), apply() and bind() functions
All these methods are defined on Function.prototype.
These methods allows to write a function once and invoke it in different context. In other words, they allows to specify the value of this which will be used while the function is being executed. They also take any parameters to be passed to the original function when it is invoked.
fun.apply(obj1 [, argsArray]) Sets obj1 as the value of this inside fun() and calls fun() passing elements of argsArray as its arguments.
fun.call(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) - Sets obj1 as the value of this inside fun() and calls fun() passing arg1, arg2, arg3, ... as its arguments.
fun.bind(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) - Returns the reference to the function fun with this inside fun bound to obj1 and parameters of fun bound to the parameters specified arg1, arg2, arg3,....
By now the difference between apply, call and bind must have become apparent. apply allows to specify the arguments to function as array-like object i.e. an object with a numeric length property and corresponding non-negative integer properties. Whereas call allows to specify the arguments to the function directly. Both apply and call immediately invokes the function in the specified context and with the specified arguments. On the other hand, bind simply returns the function bound to the specified this value and the arguments. We can capture the reference to this returned function by assigning it to a variable and later we can call it any time.
function add(inc1, inc2)
{
return this.a + inc1 + inc2;
}
var o = { a : 4 };
document.write(add.call(o, 5, 6)+"<br />"); //15
//above add.call(o,5,6) sets `this` inside
//add() to `o` and calls add() resulting:
// this.a + inc1 + inc2 =
// `o.a` i.e. 4 + 5 + 6 = 15
document.write(add.apply(o, [5, 6]) + "<br />"); //15
// `o.a` i.e. 4 + 5 + 6 = 15
var g = add.bind(o, 5, 6); //g: `o.a` i.e. 4 + 5 + 6
document.write(g()+"<br />"); //15
var h = add.bind(o, 5); //h: `o.a` i.e. 4 + 5 + ?
document.write(h(6) + "<br />"); //15
// 4 + 5 + 6 = 15
document.write(h() + "<br />"); //NaN
//no parameter is passed to h()
//thus inc2 inside add() is `undefined`
//4 + 5 + undefined = NaN</code>
7. this inside event handlers
When you assign function directly to event handlers of an element, use of this directly inside event handling function refers to the corresponding element. Such direct function assignment can be done using addeventListener method or through the traditional event registration methods like onclick.
Similarly, when you use this directly inside the event property (like <button onclick="...this..." >) of the element, it refers to the element.
However use of this indirectly through the other function called inside the event handling function or event property resolves to the global object window.
The same above behavior is achieved when we attach the function to the event handler using Microsoft's Event Registration model method attachEvent. Instead of assigning the function to the event handler (and the thus making the function method of the element), it calls the function on the event (effectively calling it in global context).
I recommend to better try this in JSFiddle.
<script>
function clickedMe() {
alert(this + " : " + this.tagName + " : " + this.id);
}
document.getElementById("button1").addEventListener("click", clickedMe, false);
document.getElementById("button2").onclick = clickedMe;
document.getElementById("button5").attachEvent('onclick', clickedMe);
</script>
<h3>Using `this` "directly" inside event handler or event property</h3>
<button id="button1">click() "assigned" using addEventListner() </button><br />
<button id="button2">click() "assigned" using click() </button><br />
<button id="button3" onclick="alert(this+ ' : ' + this.tagName + ' : ' + this.id);">used `this` directly in click event property</button>
<h3>Using `this` "indirectly" inside event handler or event property</h3>
<button onclick="alert((function(){return this + ' : ' + this.tagName + ' : ' + this.id;})());">`this` used indirectly, inside function <br /> defined & called inside event property</button><br />
<button id="button4" onclick="clickedMe()">`this` used indirectly, inside function <br /> called inside event property</button> <br />
IE only: <button id="button5">click() "attached" using attachEvent() </button>
8. this in ES6 arrow function
In an arrow function, this will behave like common variables: it will be inherited from its lexical scope. The function's this, where the arrow function is defined, will be the arrow function's this.
So, that's the same behavior as:
(function(){}).bind(this)
See the following code:
const globalArrowFunction = () => {
return this;
};
console.log(globalArrowFunction()); //window
const contextObject = {
method1: () => {return this},
method2: function(){
return () => {return this};
}
};
console.log(contextObject.method1()); //window
const contextLessFunction = contextObject.method1;
console.log(contextLessFunction()); //window
console.log(contextObject.method2()()) //contextObject
const innerArrowFunction = contextObject.method2();
console.log(innerArrowFunction()); //contextObject

Javascript's this
Simple function invocation
Consider the following function:
function foo() {
console.log("bar");
console.log(this);
}
foo(); // calling the function
Note that we are running this in the normal mode, i.e. strict mode is not used.
When running in a browser, the value of this would be logged as window. This is because window is the global variable in a web browser's scope.
If you run this same piece of code in an environment like node.js, this would refer to the global variable in your app.
Now if we run this in strict mode by adding the statement "use strict"; to the beginning of the function declaration, this would no longer refer to the global variable in either of the environments. This is done to avoid confusions in strict mode. this would, in this case just log undefined, because that is what it is, it is not defined.
In the following cases, we would see how to manipulate the value of this.
Calling a function on an object
There are different ways to do this. If you have called native methods in Javascript like forEach and slice, you should already know that the this variable in that case refers to the Object on which you called that function (Note that in javascript, just about everything is an Object, including Arrays and Functions). Take the following code for example.
var myObj = {key: "Obj"};
myObj.logThis = function () {
// I am a method
console.log(this);
}
myObj.logThis(); // myObj is logged
If an Object contains a property which holds a Function, the property is called a method. This method, when called, will always have it's this variable set to the Object it is associated with. This is true for both strict and non-strict modes.
Note that if a method is stored (or rather, copied) in another variable, the reference to this is no longer preserved in the new variable. For example:
// continuing with the previous code snippet
var myVar = myObj.logThis;
myVar();
// logs either of window/global/undefined based on mode of operation
Considering a more commonly practical scenario:
var el = document.getElementById('idOfEl');
el.addEventListener('click', function() { console.log(this) });
// the function called by addEventListener contains this as the reference to the element
// so clicking on our element would log that element itself
The new keyword
Consider a constructor function in Javascript:
function Person (name) {
this.name = name;
this.sayHello = function () {
console.log ("Hello", this);
}
}
var awal = new Person("Awal");
awal.sayHello();
// In `awal.sayHello`, `this` contains the reference to the variable `awal`
How does this work? Well, let's see what happens when we use the new keyword.
Calling the function with the new keyword would immediately initialize an Object of type Person.
The constructor of this Object has its constructor set to Person. Also, note that typeof awal would return Object only.
This new Object would be assigned the prototype of Person.prototype. This means that any method or property in the Person prototype would be available to all instances of Person, including awal.
The function Person itself is now invoked; this being a reference to the newly constructed object awal.
Pretty straightforward, eh?
Note that the official ECMAScript spec nowhere states that such types of functions are actual constructor functions. They are just normal functions, and new can be used on any function. It's just that we use them as such, and so we call them as such only.
Calling functions on Functions: call and apply
So yeah, since functions are also Objects (and in-fact first class variables in Javascript), even functions have methods which are... well, functions themselves.
All functions inherit from the global Function, and two of its many methods are call and apply, and both can be used to manipulate the value of this in the function on which they are called.
function foo () { console.log (this, arguments); }
var thisArg = {myObj: "is cool"};
foo.call(thisArg, 1, 2, 3);
This is a typical example of using call. It basically takes the first parameter and sets this in the function foo as a reference to thisArg. All other parameters passed to call is passed to the function foo as arguments.
So the above code will log {myObj: "is cool"}, [1, 2, 3] in the console. Pretty nice way to change the value of this in any function.
apply is almost the same as call accept that it takes only two parameters: thisArg and an array which contains the arguments to be passed to the function. So the above call call can be translated to apply like this:
foo.apply(thisArg, [1,2,3])
Note that call and apply can override the value of this set by dot method invocation we discussed in the second bullet.
Simple enough :)
Presenting.... bind!
bind is a brother of call and apply. It is also a method inherited by all functions from the global Function constructor in Javascript. The difference between bind and call/apply is that both call and apply will actually invoke the function. bind, on the other hand, returns a new function with the thisArg and arguments pre-set. Let's take an example to better understand this:
function foo (a, b) {
console.log (this, arguments);
}
var thisArg = {myObj: "even more cool now"};
var bound = foo.bind(thisArg, 1, 2);
console.log (typeof bound); // logs `function`
console.log (bound);
/* logs `function () { native code }` */
bound(); // calling the function returned by `.bind`
// logs `{myObj: "even more cool now"}, [1, 2]`
See the difference between the three? It is subtle, but they are used differently. Like call and apply, bind will also over-ride the value of this set by dot-method invocation.
Also note that neither of these three functions do any change to the original function. call and apply would return the value from freshly constructed functions while bind will return the freshly constructed function itself, ready to be called.
Extra stuff, copy this
Sometimes, you don't like the fact that this changes with scope, especially nested scope. Take a look at the following example.
var myObj = {
hello: function () {
return "world"
},
myMethod: function () {
// copy this, variable names are case-sensitive
var that = this;
// callbacks ftw \o/
foo.bar("args", function () {
// I want to call `hello` here
this.hello(); // error
// but `this` references to `foo` damn!
// oh wait we have a backup \o/
that.hello(); // "world"
});
}
};
In the above code, we see that the value of this changed with the nested scope, but we wanted the value of this from the original scope. So we 'copied' this to that and used the copy instead of this. Clever, eh?
Index:
What is held in this by default?
What if we call the function as a method with Object-dot notation?
What if we use the new keyword?
How do we manipulate this with call and apply?
Using bind.
Copying this to solve nested-scope issues.

"this" is all about scope. Every function has its own scope, and since everything in JS is an object, even a function can store some values into itself using "this". OOP 101 teaches that "this" is only applicable to instances of an object. Therefore, every-time a function executes, a new "instance" of that function has a new meaning of "this".
Most people get confused when they try to use "this" inside of anonymous closure functions like:
(function(value) {
this.value = value;
$('.some-elements').each(function(elt){
elt.innerHTML = this.value; // uh oh!! possibly undefined
});
})(2);
So here, inside each(), "this" doesn't hold the "value" that you expect it to (from this.value = value; above it). So, to get over this (no pun intended) problem, a developer could:
(function(value) {
var self = this; // small change
self.value = value;
$('.some-elements').each(function(elt){
elt.innerHTML = self.value; // phew!! == 2
});
})(2);
Try it out; you'll begin to like this pattern of programming

Since this thread has bumped up, I have compiled few points for readers new to this topic.
How is the value of this determined?
We use this similar to the way we use pronouns in natural languages like English: “John is running fast because he is trying to catch the train.” Instead we could have written “… John is trying to catch the train”.
var person = {
firstName: "Penelope",
lastName: "Barrymore",
fullName: function () {
// We use "this" just as in the sentence above:
console.log(this.firstName + " " + this.lastName);
// We could have also written:
console.log(person.firstName + " " + person.lastName);
}
}
this is not assigned a value until an object invokes the function where it is defined. In the global scope, all global variables and functions are defined on the window object. Therefore, this in a global function refers to (and has the value of) the global window object.
When use strict, this in global and in anonymous functions that are not bound to any object holds a value of undefined.
The this keyword is most misunderstood when: 1) we borrow a method that uses this, 2) we assign a method that uses this to a variable, 3) a function that uses this is passed as a callback function, and 4) this is used inside a closure — an inner function. (2)
What holds the future
Defined in ECMA Script 6, arrow-functions adopt the this binding from the
enclosing (function or global) scope.
function foo() {
// return an arrow function
return (a) => {
// `this` here is lexically inherited from `foo()`
console.log(this.a);
};
}
var obj1 = { a: 2 };
var obj2 = { a: 3 };
var bar = foo.call(obj1);
bar.call( obj2 ); // 2, not 3!
While arrow-functions provide an alternative to using bind(), it’s important to note that they essentially are disabling the traditional this mechanism in favor of more widely understood lexical scoping. (1)
References:
this & Object Prototypes, by Kyle Simpson. © 2014 Getify Solutions.
javascriptissexy.com - http://goo.gl/pvl0GX
Angus Croll - http://goo.gl/Z2RacU

this in JavaScript always refers to the 'owner' of the function that is being executed.
If no explicit owner is defined, then the top most owner, the window object, is referenced.
So if I did
function someKindOfFunction() {
this.style = 'foo';
}
element.onclick = someKindOfFunction;
this would refer to the element object. But be careful, a lot of people make this mistake.
<element onclick="someKindOfFunction()">
In the latter case, you merely reference the function, not hand it over to the element. Therefore, this will refer to the window object.

Every execution context in javascript has a this parameter that is set by:
How the function is called (including as an object method, use of call and apply, use of new)
Use of bind
Lexically for arrow functions (they adopt the this of their outer execution context)
Whether the code is in strict or non-strict mode
Whether the code was invoked using eval
You can set the value of this using func.call, func.apply or func.bind.
By default, and what confuses most beginners, when a listener is called after an event is raised on a DOM element, the this value of the function is the DOM element.
jQuery makes this trivial to change with jQuery.proxy.

Daniel, awesome explanation! A couple of words on this and good list of this execution context pointer in case of event handlers.
In two words, this in JavaScript points the object from whom (or from whose execution context) the current function was run and it's always read-only, you can't set it anyway (such an attempt will end up with 'Invalid left-hand side in assignment' message.
For event handlers: inline event handlers, such as <element onclick="foo">, override any other handlers attached earlier and before, so be careful and it's better to stay off of inline event delegation at all.
And thanks to Zara Alaverdyan who inspired me to this list of examples through a dissenting debate :)
el.onclick = foo; // in the foo - obj
el.onclick = function () {this.style.color = '#fff';} // obj
el.onclick = function() {doSomething();} // In the doSomething -
Window
el.addEventListener('click',foo,false) // in the foo - obj
el.attachEvent('onclick, function () { // this }') // window, all the
compliance to IE :)
<button onclick="this.style.color = '#fff';"> // obj
<button onclick="foo"> // In the foo - window, but you can <button
onclick="foo(this)">

Here is one good source of this in JavaScript.
Here is the summary:
global this
In a browser, at the global scope, this is the windowobject
<script type="text/javascript">
console.log(this === window); // true
var foo = "bar";
console.log(this.foo); // "bar"
console.log(window.foo); // "bar"
In node using the repl, this is the top namespace. You can refer to it as global.
>this
{ ArrayBuffer: [Function: ArrayBuffer],
Int8Array: { [Function: Int8Array] BYTES_PER_ELEMENT: 1 },
Uint8Array: { [Function: Uint8Array] BYTES_PER_ELEMENT: 1 },
...
>global === this
true
In node executing from a script, this at the global scope starts as an empty object. It is not the same as global
\\test.js
console.log(this); \\ {}
console.log(this === global); \\ fasle
function this
Except in the case of DOM event handlers or when a thisArg is provided (see further down), both in node and in a browser using this in a function that is not called with new references the global scope…
<script type="text/javascript">
foo = "bar";
function testThis() {
this.foo = "foo";
}
console.log(this.foo); //logs "bar"
testThis();
console.log(this.foo); //logs "foo"
</script>
If you use use strict;, in which case this will be undefined
<script type="text/javascript">
foo = "bar";
function testThis() {
"use strict";
this.foo = "foo";
}
console.log(this.foo); //logs "bar"
testThis(); //Uncaught TypeError: Cannot set property 'foo' of undefined
</script>
If you call a function with new the this will be a new context, it will not reference the global this.
<script type="text/javascript">
foo = "bar";
function testThis() {
this.foo = "foo";
}
console.log(this.foo); //logs "bar"
new testThis();
console.log(this.foo); //logs "bar"
console.log(new testThis().foo); //logs "foo"
</script>
prototype this
Functions you create become function objects. They automatically get a special prototype property, which is something you can assign values to. When you create an instance by calling your function with new you get access to the values you assigned to the prototype property. You access those values using this.
function Thing() {
console.log(this.foo);
}
Thing.prototype.foo = "bar";
var thing = new Thing(); //logs "bar"
console.log(thing.foo); //logs "bar"
It is usually a mistake to assign arrays or objects on the prototype. If you want instances to each have their own arrays, create them in the function, not the prototype.
function Thing() {
this.things = [];
}
var thing1 = new Thing();
var thing2 = new Thing();
thing1.things.push("foo");
console.log(thing1.things); //logs ["foo"]
console.log(thing2.things); //logs []
object this
You can use this in any function on an object to refer to other properties on that object. This is not the same as an instance created with new.
var obj = {
foo: "bar",
logFoo: function () {
console.log(this.foo);
}
};
obj.logFoo(); //logs "bar"
DOM event this
In an HTML DOM event handler, this is always a reference to the DOM element the event was attached to
function Listener() {
document.getElementById("foo").addEventListener("click",
this.handleClick);
}
Listener.prototype.handleClick = function (event) {
console.log(this); //logs "<div id="foo"></div>"
}
var listener = new Listener();
document.getElementById("foo").click();
Unless you bind the context
function Listener() {
document.getElementById("foo").addEventListener("click",
this.handleClick.bind(this));
}
Listener.prototype.handleClick = function (event) {
console.log(this); //logs Listener {handleClick: function}
}
var listener = new Listener();
document.getElementById("foo").click();
HTML this
Inside HTML attributes in which you can put JavaScript, this is a reference to the element.
<div id="foo" onclick="console.log(this);"></div>
<script type="text/javascript">
document.getElementById("foo").click(); //logs <div id="foo"...
</script>
eval this
You can use eval to access this.
function Thing () {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
eval("console.log(this.foo)"); //logs "bar"
}
var thing = new Thing();
thing.logFoo();
with this
You can use with to add this to the current scope to read and write to values on this without referring to this explicitly.
function Thing () {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
with (this) {
console.log(foo);
foo = "foo";
}
}
var thing = new Thing();
thing.logFoo(); // logs "bar"
console.log(thing.foo); // logs "foo"
jQuery this
the jQuery will in many places have this refer to a DOM element.
<div class="foo bar1"></div>
<div class="foo bar2"></div>
<script type="text/javascript">
$(".foo").each(function () {
console.log(this); //logs <div class="foo...
});
$(".foo").on("click", function () {
console.log(this); //logs <div class="foo...
});
$(".foo").each(function () {
this.click();
});
</script>

There is a lot of confusion regarding how "this" keyword is interpreted in JavaScript. Hopefully this article will lay all those to rest once and for all. And a lot more. Please read the entire article carefully. Be forewarned that this article is long.
Irrespective of the context in which it is used, "this" always references the "current object" in Javascript. However, what the "current object" is differs according to context. The context may be exactly 1 of the 6 following:
Global (i.e. Outside all functions)
Inside Direct "Non Bound Function" Call (i.e. a function that has not been bound by calling functionName.bind)
Inside Indirect "Non Bound Function" Call through functionName.call and functionName.apply
Inside "Bound Function" Call (i.e. a function that has been bound by calling functionName.bind)
While Object Creation through "new"
Inside Inline DOM event handler
The following describes each of this contexts one by one:
Global Context (i.e. Outside all functions):
Outside all functions (i.e. in global context) the "current
object" (and hence the value of "this") is always the
"window" object for browsers.
Inside Direct "Non Bound Function" Call:
Inside a Direct "Non Bound Function" Call, the object that
invoked the function call becomes the "current object" (and hence
the value of "this"). If a function is called without a explicit current object, the current object is either the "window" object (For Non Strict Mode) or undefined (For Strict Mode) . Any function (or variable) defined in
Global Context automatically becomes a property of the "window" object.For e.g Suppose function is defined in Global Context as
function UserDefinedFunction(){
alert(this)
}
it becomes the property of the window object, as if you have defined
it as
window.UserDefinedFunction=function(){
alert(this)
}
In "Non Strict Mode", Calling/Invoking this function directly through "UserDefinedFunction()" will automatically call/invoke
it as "window.UserDefinedFunction()" making "window" as the
"current object" (and hence the value of "this") within "UserDefinedFunction".Invoking this function in "Non Strict Mode" will result in the following
UserDefinedFunction() // displays [object Window] as it automatically gets invoked as window.UserDefinedFunction()
In "Strict Mode", Calling/Invoking the function directly through
"UserDefinedFunction()" will "NOT" automatically call/invoke it as "window.UserDefinedFunction()".Hence the "current
object" (and the value of "this") within
"UserDefinedFunction" shall be undefined. Invoking this function in "Strict Mode" will result in the following
UserDefinedFunction() // displays undefined
However, invoking it explicitly using window object shall result in
the following
window.UserDefinedFunction() // "always displays [object Window] irrespective of mode."
Let us look at another example. Please look at the following code
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction
}
var o2={
c:3,
d:4,
f:UserDefinedFunction
}
o1.f() // Shall display 1,2,undefined,undefined
o2.f() // Shall display undefined,undefined,3,4
In the above example we see that when "UserDefinedFunction" was
invoked through o1, "this" takes value of o1 and the
value of its properties "a" and "b" get displayed. The value
of "c" and "d" were shown as undefined as o1 does
not define these properties
Similarly when "UserDefinedFunction" was invoked through o2,
"this" takes value of o2 and the value of its properties "c" and "d" get displayed.The value of "a" and "b" were shown as undefined as o2 does not define these properties.
Inside Indirect "Non Bound Function" Call through functionName.call and functionName.apply:
When a "Non Bound Function" is called through
functionName.call or functionName.apply, the "current object" (and hence the value of "this") is set to the value of
"this" parameter (first parameter) passed to call/apply. The following code demonstrates the same.
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction
}
var o2={
c:3,
d:4,
f:UserDefinedFunction
}
UserDefinedFunction.call(o1) // Shall display 1,2,undefined,undefined
UserDefinedFunction.apply(o1) // Shall display 1,2,undefined,undefined
UserDefinedFunction.call(o2) // Shall display undefined,undefined,3,4
UserDefinedFunction.apply(o2) // Shall display undefined,undefined,3,4
o1.f.call(o2) // Shall display undefined,undefined,3,4
o1.f.apply(o2) // Shall display undefined,undefined,3,4
o2.f.call(o1) // Shall display 1,2,undefined,undefined
o2.f.apply(o1) // Shall display 1,2,undefined,undefined
The above code clearly shows that the "this" value for any "NON
Bound Function" can be altered through call/apply. Also,if the
"this" parameter is not explicitly passed to call/apply, "current object" (and hence the value of "this") is set to "window" in Non strict mode and "undefined" in strict mode.
Inside "Bound Function" Call (i.e. a function that has been bound by calling functionName.bind):
A bound function is a function whose "this" value has been
fixed. The following code demonstrated how "this" works in case
of bound function
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction,
bf:null
}
var o2={
c:3,
d:4,
f:UserDefinedFunction,
bf:null
}
var bound1=UserDefinedFunction.bind(o1); // permanantly fixes "this" value of function "bound1" to Object o1
bound1() // Shall display 1,2,undefined,undefined
var bound2=UserDefinedFunction.bind(o2); // permanantly fixes "this" value of function "bound2" to Object o2
bound2() // Shall display undefined,undefined,3,4
var bound3=o1.f.bind(o2); // permanantly fixes "this" value of function "bound3" to Object o2
bound3() // Shall display undefined,undefined,3,4
var bound4=o2.f.bind(o1); // permanantly fixes "this" value of function "bound4" to Object o1
bound4() // Shall display 1,2,undefined,undefined
o1.bf=UserDefinedFunction.bind(o2) // permanantly fixes "this" value of function "o1.bf" to Object o2
o1.bf() // Shall display undefined,undefined,3,4
o2.bf=UserDefinedFunction.bind(o1) // permanantly fixes "this" value of function "o2.bf" to Object o1
o2.bf() // Shall display 1,2,undefined,undefined
bound1.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
bound1.apply(o2) // Shall still display 1,2,undefined,undefined. "apply" cannot alter the value of "this" for bound function
o2.bf.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
o2.bf.apply(o2) // Shall still display 1,2,undefined,undefined."apply" cannot alter the value of "this" for bound function
As given in the code above, "this" value for any "Bound Function"
CANNOT be altered through call/apply. Also, if the "this"
parameter is not explicitly passed to bind, "current object"
(and hence the value of "this" ) is set to "window" in Non
strict mode and "undefined" in strict mode. One more thing.
Binding an already bound function does not change the value of "this".
It remains set as the value set by first bind function.
While Object Creation through "new":
Inside a constructor function, the "current object" (and hence the value of
"this") references the object that is currently being created
through "new" irrespective of the bind status of the function. However
if the constructor is a bound function it shall get called with
predefined set of arguments as set for the bound function.
Inside Inline DOM event handler:
Please look at the following HTML Snippet
<button onclick='this.style.color=white'>Hello World</button>
<div style='width:100px;height:100px;' onclick='OnDivClick(event,this)'>Hello World</div>
The "this" in above examples refer to "button" element and the
"div" element respectively.
In the first example, the font color of the button shall be set to
white when it is clicked.
In the second example when the "div" element is clicked it shall
call the OnDivClick function with its second parameter
referencing the clicked div element. However the value of "this"
within OnDivClick SHALL NOT reference the clicked div
element. It shall be set as the "window object" or
"undefined" in Non strict and Strict Modes respectively (if OnDivClick is an unbound function) or set to a predefined
Bound value (if OnDivClick is a bound function)
The following summarizes the entire article
In Global Context "this" always refers to the "window" object
Whenever a function is invoked, it is invoked in context of an
object ("current object"). If the current object is not explicitly provided,
the current object is the "window object" in NON Strict
Mode and "undefined" in Strict Mode by default.
The value of "this" within a Non Bound function is the reference to object in context of which the function is invoked ("current object")
The value of "this" within a Non Bound function can be overriden by
call and apply methods of the function.
The value of "this" is fixed for a Bound function and cannot be
overriden by call and apply methods of the function.
Binding and already bound function does not change the value of "this". It remains set as the value set by first bind function.
The value of "this" within a constructor is the object that is being
created and initialized
The value of "this" within an inline DOM event handler is reference
to the element for which the event handler is given.

Probably the most detailed and comprehensive article on this is the following:
Gentle explanation of 'this' keyword in JavaScript
The idea behind this is to understand that the function invocation types have the significant importance on setting this value.
When having troubles identifying this, do not ask yourself:
Where is this taken from?
but do ask yourself:
How is the function invoked?
For an arrow function (special case of context transparency) ask yourself:
What value has this where the arrow function is defined?
This mindset is correct when dealing with this and will save you from headache.

This is the best explanation I've seen: Understand JavaScripts this with Clarity
The this reference ALWAYS refers to (and holds the value of) an
object—a singular object—and it is usually used inside a function or a
method, although it can be used outside a function in the global
scope. Note that when we use strict mode, this holds the value of
undefined in global functions and in anonymous functions that are not
bound to any object.
There are Four Scenarios where this can be confusing:
When we pass a method (that uses this) as an argument to be used as a callback function.
When we use an inner function (a closure). It is important to take note that closures cannot access the outer function’s this variable by using the this keyword because the this variable is accessible only by the function itself, not by inner functions.
When a method which relies on this is assigned to a variable across contexts, in which case this references another object than originally intended.
When using this along with the bind, apply, and call methods.
He gives code examples, explanations, and solutions, which I thought was very helpful.

this is one of the misunderstood concept in JavaScript because it behaves little differently from place to place. Simply, this refers to the "owner" of the function we are currently executing.
this helps to get the current object (a.k.a. execution context) we work with. If you understand in which object the current function is getting executed, you can understand easily what current this is
var val = "window.val"
var obj = {
val: "obj.val",
innerMethod: function () {
var val = "obj.val.inner",
func = function () {
var self = this;
return self.val;
};
return func;
},
outerMethod: function(){
return this.val;
}
};
//This actually gets executed inside window object
console.log(obj.innerMethod()()); //returns window.val
//Breakdown in to 2 lines explains this in detail
var _inn = obj.innerMethod();
console.log(_inn()); //returns window.val
console.log(obj.outerMethod()); //returns obj.val
Above we create 3 variables with same name 'val'. One in global context, one inside obj and the other inside innerMethod of obj. JavaScript resolves identifiers within a particular context by going up the scope chain from local go global.
Few places where this can be differentiated
Calling a method of a object
var status = 1;
var helper = {
status : 2,
getStatus: function () {
return this.status;
}
};
var theStatus1 = helper.getStatus(); //line1
console.log(theStatus1); //2
var theStatus2 = helper.getStatus;
console.log(theStatus2()); //1
When line1 is executed, JavaScript establishes an execution context (EC) for the function call, setting this to the object referenced by whatever came before the last ".". so in the last line you can understand that a() was executed in the global context which is the window.
With Constructor
this can be used to refer to the object being created
function Person(name){
this.personName = name;
this.sayHello = function(){
return "Hello " + this.personName;
}
}
var person1 = new Person('Scott');
console.log(person1.sayHello()); //Hello Scott
var person2 = new Person('Hugh');
var sayHelloP2 = person2.sayHello;
console.log(sayHelloP2()); //Hello undefined
When new Person() is executed, a completely new object is created. Person is called and its this is set to reference that new object.
Function call
function testFunc() {
this.name = "Name";
this.myCustomAttribute = "Custom Attribute";
return this;
}
var whatIsThis = testFunc();
console.log(whatIsThis); //window
var whatIsThis2 = new testFunc();
console.log(whatIsThis2); //testFunc() / object
console.log(window.myCustomAttribute); //Custom Attribute
If we miss new keyword, whatIsThis referes to the most global context it can find(window)
With event handlers
If the event handler is inline, this refers to global object
<script type="application/javascript">
function click_handler() {
alert(this); // alerts the window object
}
</script>
<button id='thebutton' onclick='click_handler()'>Click me!</button>
When adding event handler through JavaScript, this refers to DOM element that generated the event.
You can also manipulate the context using .apply() .call() and .bind()
JQuery proxy is another way you can use to make sure this in a function will be the value you desire. (Check Understanding $.proxy(), jQuery.proxy() usage)
What does var that = this means in JavaScript

The value of "this" depends on the "context" in which the function is executed. The context can be any object or the global object, i.e., window.
So the Semantic of "this" is different from the traditional OOP languages. And it causes problems:
1. when a function is passed to another variable (most likely, a callback); and 2. when a closure is invoked from a member method of a class.
In both cases, this is set to window.

In pseudoclassical terms, the way many lectures teach the 'this' keyword is as an object instantiated by a class or object constructor. Each time a new object is constructed from a class, imagine that under the hood a local instance of a 'this' object is created and returned. I remember it taught like this:
function Car(make, model, year) {
var this = {}; // under the hood, so to speak
this.make = make;
this.model = model;
this.year = year;
return this; // under the hood
}
var mycar = new Car('Eagle', 'Talon TSi', 1993);
// ========= under the hood
var this = {};
this.make = 'Eagle';
this.model = 'Talon TSi';
this.year = 1993;
return this;

Whould this help? (Most confusion of 'this' in javascript is coming from the fact that it generally is not linked to your object, but to the current executing scope -- that might not be exactly how it works but is always feels like that to me -- see the article for a complete explanation)

A little bit info about this keyword
Let's log this keyword to the console in global scope without any more code but
console.log(this)
In Client/Browser this keyword is a global object which is window
console.log(this === window) // true
and
In Server/Node/Javascript runtime this keyword is also a global object which is module.exports
console.log(this === module.exports) // true
console.log(this === exports) // true
Keep in mind exports is just a reference to module.exports

I have a different take on this from the other answers that I hope is helpful.
One way to look at JavaScript is to see that there are only 1 way to call a function1. It is
functionObject.call(objectForThis, arg0, arg1, arg2, ...);
There is always some value supplied for objectForThis.
Everything else is syntactic sugar for functionObject.call
So, everything else can be described by how it translates into functionObject.call.
If you just call a function then this is the "global object" which in the browser is the window
function foo() {
console.log(this);
}
foo(); // this is the window object
In other words,
foo();
was effectively translated into
foo.call(window);
Note that if you use strict mode then this will be undefined
'use strict';
function foo() {
console.log(this);
}
foo(); // this is the window object
which means
In other words,
foo();
was effectively translated into
foo.call(undefined);
In JavaScript there are operators like + and - and *. There is also the dot operator which is .
The . operator when used with a function on the right and an object on the left effectively means "pass object as this to function.
Example
const bar = {
name: 'bar',
foo() {
console.log(this);
},
};
bar.foo(); // this is bar
In other words bar.foo() translates into const temp = bar.foo; temp.call(bar);
Note that it doesn't matter how the function was created (mostly...). All of these will produce the same results
const bar = {
name: 'bar',
fn1() { console.log(this); },
fn2: function() { console.log(this); },
fn3: otherFunction,
};
function otherFunction() { console.log(this) };
bar.fn1(); // this is bar
bar.fn2(); // this is bar
bar.fn3(); // this is bar
Again these all are just syntactic sugar for
{ const temp = bar.fn1; temp.call(bar); }
{ const temp = bar.fn2; temp.call(bar); }
{ const temp = bar.fn3; temp.call(bar); }
One other wrinkle is the prototype chain. When you use a.b JavaScript first looks on the object referenced directly by a for the property b. If b is not found on the object then JavaScript will look in the object's prototype to find b.
There are various ways to define an object's prototype, the most common in 2019 is the class keyword. For the purposes of this though it doesn't matter. What matters is that as it looks in object a for property b if it finds property b on the object or in it's prototype chain if b ends up being a function then the same rules as above apply. The function b references will be called using the call method and passing a as objectForThis as shown a the top of this answer.
Now. Let's imagine we make a function that explicitly sets this before calling another function and then call it with the . (dot) operator
function foo() {
console.log(this);
}
function bar() {
const objectForThis = {name: 'moo'}
foo.call(objectForThis); // explicitly passing objectForThis
}
const obj = {
bar,
};
obj.bar();
Following the translation to use call, obj.bar() becomes const temp = obj.bar; temp.call(obj);. When we enter the bar function we call foo but we explicitly passed in another object for objectForThis so when we arrive at foo this is that inner object.
This is what both bind and => functions effectively do. They are more syntactic sugar. They effectively build a new invisible function exactly like bar above that explicitly sets this before it calls whatever function is specified. In the case of bind this is set to whatever you pass to bind.
function foo() {
console.log(this);
}
const bar = foo.bind({name: 'moo'});
// bind created a new invisible function that calls foo with the bound object.
bar();
// the objectForThis we are passing to bar here is ignored because
// the invisible function that bind created will call foo with with
// the object we bound above
bar.call({name: 'other'});
Note that if functionObject.bind did not exist we could make our own like this
function bind(fn, objectForThis) {
return function(...args) {
return fn.call(objectForthis, ...args);
};
}
and then we could call it like this
function foo() {
console.log(this);
}
const bar = bind(foo, {name:'abc'});
Arrow functions, the => operator are syntactic sugar for bind
const a = () => {console.log(this)};
is the same as
const tempFn = function() {console.log(this)};
const a = tempFn.bind(this);
Just like bind, a new invisible function is created that calls the given function with a bound value for objectForThis but unlike bind the object to be bound is implicit. It's whatever this happens to be when the => operator is used.
So, just like the rules above
const a = () => { console.log(this); } // this is the global object
'use strict';
const a = () => { console.log(this); } // this is undefined
function foo() {
return () => { console.log(this); }
}
const obj = {
foo,
};
const b = obj.foo();
b();
obj.foo() translates to const temp = obj.foo; temp.call(obj); which means the arrow operator inside foo will bind obj to a new invisible function and return that new invisible function which is assigned to b. b() will work as it always has as b.call(window) or b.call(undefined) calling the new invisible function that foo created. That invisible function ignores the this passed into it and passes obj as objectForThis` to the arrow function.
The code above translates to
function foo() {
function tempFn() {
console.log(this);
}
return tempFn.bind(this);
}
const obj = {
foo,
};
const b = obj.foo();
b.call(window or undefined if strict mode);
1apply is another function similar to call
functionName.apply(objectForThis, arrayOfArgs);
But as of ES6 conceptually you can even translate that into
functionName.call(objectForThis, ...arrayOfArgs);

"this" in JavaScript
this is one of the properties of the Execution Context.
this property is created every time a function is executed and not
before that.
Its value is not static but rather depends on how it is being used.
takes a value that points to the owner of the function in which it is
used
There are different ways in which the "this" keyword can be used, below are the example for it (method, regular function, arrow function, Event listener, Explicit function Binding).
1. Inside a method.
this === (to the object that is calling the Method).
In the above example the method " fullName()" is called by an Object "person" hence the value of this inside the method " fullName()" will be equal to the "person" Object.
2. Inside a Function.
i) function declaration/expression
in loose mode this === window (object)
in Strict mode this === undefined
Note : this property works the same while defining a function using function declaration or function expression approach.
ii) Arrow Function :
Arrow Function does not have their own this property, they take the value of this as their surrounding Function.
If the surrounding function is not present i.e if they are defined at the global level then this === window (object)
3. Event Listener
this === object on which the handler is attached.
click event bind to the Document object
In the above example since the click handler is attached to the "document" object, this will be equal to the "document" object
4. Explicit Function Binding (call, Apply, Bind)
The call() and apply() methods are predefined JavaScript methods.
They can both be used to call an object method with another object as an argument.
In the above example this inside the "printFullDetails()" is explicitly set to the personObj1 and personObj2 by passing as the first argument to call method.
You can Explore more about call, apply and bind methods here.

this use for Scope just like this
<script type="text/javascript" language="javascript">
$('#tbleName tbody tr').each(function{
var txt='';
txt += $(this).find("td").eq(0).text();
\\same as above but synatx different
var txt1='';
txt1+=$('#tbleName tbody tr').eq(0).text();
alert(txt1)
});
</script>
value of txt1 and txt is same
in Above example
$(this)=$('#tbleName tbody tr') is Same

Summary this Javascript:
The value of this is determined by how the function is invoked not, where it was created!
Usually the value of this is determined by the Object which is left of the dot. (window in global space)
In event listeners the value of this refers to the DOM element on which the event was called.
When in function is called with the new keyword the value of this refers to the newly created object
You can manipulate the value of this with the functions: call, apply, bind
Example:
let object = {
prop1: function () {console.log(this);}
}
object.prop1(); // object is left of the dot, thus this is object
const myFunction = object.prop1 // We store the function in the variable myFunction
myFunction(); // Here we are in the global space
// myFunction is a property on the global object
// Therefore it logs the window object
Example event listeners:
document.querySelector('.foo').addEventListener('click', function () {
console.log(this); // This refers to the DOM element the eventListener was invoked from
})
document.querySelector('.foo').addEventListener('click', () => {
console.log(this); // Tip, es6 arrow function don't have their own binding to the this v
}) // Therefore this will log the global object
.foo:hover {
color: red;
cursor: pointer;
}
<div class="foo">click me</div>
Example constructor:
function Person (name) {
this.name = name;
}
const me = new Person('Willem');
// When using the new keyword the this in the constructor function will refer to the newly created object
console.log(me.name);
// Therefore, the name property was placed on the object created with new keyword.

To understand "this" properly one must understand the context and scope and difference between them.
Scope: In javascript scope is related to the visibility of the variables, scope achieves through the use of the function. (Read more about scope)
Context: Context is related to objects. It refers to the object to which a function belongs. When you use the JavaScript “this” keyword, it refers to the object to which function belongs. For example, inside of a function, when you say: “this.accoutNumber”, you are referring to the property “accoutNumber”, that belongs to the object to which that function belongs.
If the object “myObj” has a method called “getMyName”, when the JavaScript keyword “this” is used inside of “getMyName”, it refers to “myObj”. If the function “getMyName” were executed in the global scope, then “this” refers to the window object (except in strict mode).
Now let's see some example:
<script>
console.log('What is this: '+this);
console.log(this);
</script>
Runnig abobve code in browser output will:
According to the output you are inside of the context of the window object, it is also visible that window prototype refers to the Object.
Now let's try inside of a function:
<script>
function myFunc(){
console.log('What is this: '+this);
console.log(this);
}
myFunc();
</script>
Output:
The output is the same because we logged 'this' variable in the global scope and we logged it in functional scope, we didn't change the context. In both case context was same, related to widow object.
Now let's create our own object. In javascript, you can create an object in many ways.
<script>
var firstName = "Nora";
var lastName = "Zaman";
var myObj = {
firstName:"Lord",
lastName:'Baron',
printNameGetContext:function(){
console.log(firstName + " "+lastName);
console.log(this.firstName +" "+this.lastName);
return this;
}
}
var context = myObj.printNameGetContext();
console.log(context);
</script>
Output:
So from the above example, we found that 'this' keyword is referring to a new context that is related to myObj, and myObject also has prototype chain to Object.
Let's go throw another example:
<body>
<button class="btn">Click Me</button>
<script>
function printMe(){
//Terminal2: this function declared inside window context so this function belongs to the window object.
console.log(this);
}
document.querySelector('.btn').addEventListener('click', function(){
//Terminal1: button context, this callback function belongs to DOM element
console.log(this);
printMe();
})
</script>
</body>
output:
Make sense right? (read comments)
If you having trouble to understand the above example let's try with our own callback;
<script>
var myObj = {
firstName:"Lord",
lastName:'Baron',
printName:function(callback1, callback2){
//Attaching callback1 with this myObj context
this.callback1 = callback1;
this.callback1(this.firstName +" "+this.lastName)
//We did not attached callback2 with myObj so, it's reamin with window context by default
callback2();
/*
//test bellow codes
this.callback2 = callback2;
this.callback2();
*/
}
}
var callback2 = function (){
console.log(this);
}
myObj.printName(function(data){
console.log(data);
console.log(this);
}, callback2);
</script>
output:
Now let's Understand Scope, Self, IIFE and THIS how behaves
var color = 'red'; // property of window
var obj = {
color:'blue', // property of window
printColor: function(){ // property of obj, attached with obj
var self = this;
console.log('In printColor -- this.color: '+this.color);
console.log('In printColor -- self.color: '+self.color);
(function(){ // decleard inside of printColor but not property of object, it will executed on window context.
console.log(this)
console.log('In IIFE -- this.color: '+this.color);
console.log('In IIFE -- self.color: '+self.color);
})();
function nestedFunc(){// decleard inside of printColor but not property of object, it will executed on window context.
console.log('nested fun -- this.color: '+this.color);
console.log('nested fun -- self.color: '+self.color);
}
nestedFunc(); // executed on window context
return nestedFunc;
}
};
obj.printColor()(); // returned function executed on window context
</script>
Output is pretty awesome right?

Related

Why variables declared without useState do have a state in functional components? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?
I have seen the Scheme example given on Wikipedia, but unfortunately it did not help.
A closure is a pairing of:
A function and
A reference to that function's outer scope (lexical environment)
A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.
Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.
If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.
In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret:
function foo() {
const secret = Math.trunc(Math.random() * 100)
return function inner() {
console.log(`The secret number is ${secret}.`)
}
}
const f = foo() // `secret` is not directly accessible from outside `foo`
f() // The only way to retrieve `secret`, is to invoke `f`
In other words: in JavaScript, functions carry a reference to a private "box of state", to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.
And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.
If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier.
So, if you want a function to always have access to a private piece of state, you can use a closure.
...and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality.
In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret remains available to the function object inner, after it has been returned from foo.
Uses of Closures
Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.
Private Instance Variables
In the following code, the function toString closes over the details of the car.
function Car(manufacturer, model, year, color) {
return {
toString() {
return `${manufacturer} ${model} (${year}, ${color})`
}
}
}
const car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver')
console.log(car.toString())
Functional Programming
In the following code, the function inner closes over both fn and args.
function curry(fn) {
const args = []
return function inner(arg) {
if(args.length === fn.length) return fn(...args)
args.push(arg)
return inner
}
}
function add(a, b) {
return a + b
}
const curriedAdd = curry(add)
console.log(curriedAdd(2)(3)()) // 5
Event-Oriented Programming
In the following code, function onClick closes over variable BACKGROUND_COLOR.
const $ = document.querySelector.bind(document)
const BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)'
function onClick() {
$('body').style.background = BACKGROUND_COLOR
}
$('button').addEventListener('click', onClick)
<button>Set background color</button>
Modularization
In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick and toString close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our code.
let namespace = {};
(function foo(n) {
let numbers = []
function format(n) {
return Math.trunc(n)
}
function tick() {
numbers.push(Math.random() * 100)
}
function toString() {
return numbers.map(format)
}
n.counter = {
tick,
toString
}
}(namespace))
const counter = namespace.counter
counter.tick()
counter.tick()
console.log(counter.toString())
Examples
Example 1
This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves. It is as though the stack-frame stays alive in memory even after the outer function exits.
function foo() {
let x = 42
let inner = () => console.log(x)
x = x + 1
return inner
}
foo()() // logs 43
Example 2
In the following code, three methods log, increment, and update all close over the same lexical environment.
And every time createObject is called, a new execution context (stack frame) is created and a completely new variable x, and a new set of functions (log etc.) are created, that close over this new variable.
function createObject() {
let x = 42;
return {
log() { console.log(x) },
increment() { x++ },
update(value) { x = value }
}
}
const o = createObject()
o.increment()
o.log() // 43
o.update(5)
o.log() // 5
const p = createObject()
p.log() // 42
Example 3
If you are using variables declared using var, be careful you understand which variable you are closing over. Variables declared using var are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let and const.
In the following code, each time around the loop, a new function inner is created, which closes over i. But because var i is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i (3) is printed, three times.
function foo() {
var result = []
for (var i = 0; i < 3; i++) {
result.push(function inner() { console.log(i) } )
}
return result
}
const result = foo()
// The following will print `3`, three times...
for (var i = 0; i < 3; i++) {
result[i]()
}
Final points:
Whenever a function is declared in JavaScript closure is created.
Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using eval('var foo = …').
When you use new Function(…) (the Function constructor) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
A closure in JavaScript is like keeping a reference (NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
A new set of local variables is created every time a function is called.
Links
Douglas Crockford's simulated private attributes and private methods for an object, using closures.
A great explanation of how closures can cause memory leaks in IE if you are not careful.
MDN documentation on JavaScript Closures.
Every function in JavaScript maintains a link to its outer lexical environment. A lexical environment is a map of all the names (eg. variables, parameters) within a scope, with their values.
So, whenever you see the function keyword, code inside that function has access to variables declared outside the function.
function foo(x) {
var tmp = 3;
function bar(y) {
console.log(x + y + (++tmp)); // will log 16
}
bar(10);
}
foo(2);
This will log 16 because function bar closes over the parameter x and the variable tmp, both of which exist in the lexical environment of outer function foo.
Function bar, together with its link with the lexical environment of function foo is a closure.
A function doesn't have to return in order to create a closure. Simply by virtue of its declaration, every function closes over its enclosing lexical environment, forming a closure.
function foo(x) {
var tmp = 3;
return function (y) {
console.log(x + y + (++tmp)); // will also log 16
}
}
var bar = foo(2);
bar(10); // 16
bar(10); // 17
The above function will also log 16, because the code inside bar can still refer to argument x and variable tmp, even though they are no longer directly in scope.
However, since tmp is still hanging around inside bar's closure, it is available to be incremented. It will be incremented each time you call bar.
The simplest example of a closure is this:
var a = 10;
function test() {
console.log(a); // will output 10
console.log(b); // will output 6
}
var b = 6;
test();
When a JavaScript function is invoked, a new execution context ec is created. Together with the function arguments and the target object, this execution context also receives a link to the lexical environment of the calling execution context, meaning the variables declared in the outer lexical environment (in the above example, both a and b) are available from ec.
Every function creates a closure because every function has a link to its outer lexical environment.
Note that variables themselves are visible from within a closure, not copies.
FOREWORD: this answer was written when the question was:
Like the old Albert said : "If you can't explain it to a six-year old, you really don't understand it yourself.”. Well I tried to explain JS closures to a 27 years old friend and completely failed.
Can anybody consider that I am 6 and strangely interested in that subject ?
I'm pretty sure I was one of the only people that attempted to take the initial question literally. Since then, the question has mutated several times, so my answer may now seem incredibly silly & out of place. Hopefully the general idea of the story remains fun for some.
I'm a big fan of analogy and metaphor when explaining difficult concepts, so let me try my hand with a story.
Once upon a time:
There was a princess...
function princess() {
She lived in a wonderful world full of adventures. She met her Prince Charming, rode around her world on a unicorn, battled dragons, encountered talking animals, and many other fantastical things.
var adventures = [];
function princeCharming() { /* ... */ }
var unicorn = { /* ... */ },
dragons = [ /* ... */ ],
squirrel = "Hello!";
/* ... */
But she would always have to return back to her dull world of chores and grown-ups.
return {
And she would often tell them of her latest amazing adventure as a princess.
story: function() {
return adventures[adventures.length - 1];
}
};
}
But all they would see is a little girl...
var littleGirl = princess();
...telling stories about magic and fantasy.
littleGirl.story();
And even though the grown-ups knew of real princesses, they would never believe in the unicorns or dragons because they could never see them. The grown-ups said that they only existed inside the little girl's imagination.
But we know the real truth; that the little girl with the princess inside...
...is really a princess with a little girl inside.
Taking the question seriously, we should find out what a typical 6-year-old is capable of cognitively, though admittedly, one who is interested in JavaScript is not so typical.
On Childhood Development: 5 to 7 Years it says:
Your child will be able to follow two-step directions. For example, if you say to your child, "Go to the kitchen and get me a trash bag" they will be able to remember that direction.
We can use this example to explain closures, as follows:
The kitchen is a closure that has a local variable, called trashBags. There is a function inside the kitchen called getTrashBag that gets one trash bag and returns it.
We can code this in JavaScript like this:
function makeKitchen() {
var trashBags = ['A', 'B', 'C']; // only 3 at first
return {
getTrashBag: function() {
return trashBags.pop();
}
};
}
var kitchen = makeKitchen();
console.log(kitchen.getTrashBag()); // returns trash bag C
console.log(kitchen.getTrashBag()); // returns trash bag B
console.log(kitchen.getTrashBag()); // returns trash bag A
Further points that explain why closures are interesting:
Each time makeKitchen() is called, a new closure is created with its own separate trashBags.
The trashBags variable is local to the inside of each kitchen and is not accessible outside, but the inner function on the getTrashBag property does have access to it.
Every function call creates a closure, but there would be no need to keep the closure around unless an inner function, which has access to the inside of the closure, can be called from outside the closure. Returning the object with the getTrashBag function does that here.
The Straw Man
I need to know how many times a button has been clicked and do something on every third click...
Fairly Obvious Solution
// Declare counter outside event handler's scope
var counter = 0;
var element = document.getElementById('button');
element.addEventListener("click", function() {
// Increment outside counter
counter++;
if (counter === 3) {
// Do something every third time
console.log("Third time's the charm!");
// Reset counter
counter = 0;
}
});
<button id="button">Click Me!</button>
Now this will work, but it does encroach into the outer scope by adding a variable, whose sole purpose is to keep track of the count. In some situations, this would be preferable as your outer application might need access to this information. But in this case, we are only changing every third click's behavior, so it is preferable to enclose this functionality inside the event handler.
Consider this option
var element = document.getElementById('button');
element.addEventListener("click", (function() {
// init the count to 0
var count = 0;
return function(e) { // <- This function becomes the click handler
count++; // and will retain access to the above `count`
if (count === 3) {
// Do something every third time
console.log("Third time's the charm!");
//Reset counter
count = 0;
}
};
})());
<button id="button">Click Me!</button>
Notice a few things here.
In the above example, I am using the closure behavior of JavaScript. This behavior allows any function to have access to the scope in which it was created, indefinitely. To practically apply this, I immediately invoke a function that returns another function, and because the function I'm returning has access to the internal count variable (because of the closure behavior explained above) this results in a private scope for usage by the resulting function... Not so simple? Let's dilute it down...
A simple one-line closure
// _______________________Immediately invoked______________________
// | |
// | Scope retained for use ___Returned as the____ |
// | only by returned function | value of func | |
// | | | | | |
// v v v v v v
var func = (function() { var a = 'val'; return function() { alert(a); }; })();
All variables outside the returned function are available to the returned function, but they are not directly available to the returned function object...
func(); // Alerts "val"
func.a; // Undefined
Get it? So in our primary example, the count variable is contained within the closure and always available to the event handler, so it retains its state from click to click.
Also, this private variable state is fully accessible, for both readings and assigning to its private scoped variables.
There you go; you're now fully encapsulating this behavior.
Full Blog Post (including jQuery considerations)
Closures are hard to explain because they are used to make some behaviour work that everybody intuitively expects to work anyway. I find the best way to explain them (and the way that I learned what they do) is to imagine the situation without them:
const makePlus = function(x) {
return function(y) { return x + y; };
}
const plus5 = makePlus(5);
console.log(plus5(3));
What would happen here if JavaScript didn't know closures? Just replace the call in the last line by its method body (which is basically what function calls do) and you get:
console.log(x + 3);
Now, where's the definition of x? We didn't define it in the current scope. The only solution is to let plus5 carry its scope (or rather, its parent's scope) around. This way, x is well-defined and it is bound to the value 5.
TLDR
A closure is a link between a function and its outer lexical (ie. as-written) environment, such that the identifiers (variables, parameters, function declarations etc) defined within that environment are visible from within the function, regardless of when or from where the function is invoked.
Details
In the terminology of the ECMAScript specification, a closure can be said to be implemented by the [[Environment]] reference of every function-object, which points to the lexical environment within which the function is defined.
When a function is invoked via the internal [[Call]] method, the [[Environment]] reference on the function-object is copied into the outer environment reference of the environment record of the newly-created execution context (stack frame).
In the following example, function f closes over the lexical environment of the global execution context:
function f() {}
In the following example, function h closes over the lexical environment of function g, which, in turn, closes over the lexical environment of the global execution context.
function g() {
function h() {}
}
If an inner function is returned by an outer, then the outer lexical environment will persist after the outer function has returned. This is because the outer lexical environment needs to be available if the inner function is eventually invoked.
In the following example, function j closes over the lexical environment of function i, meaning that variable x is visible from inside function j, long after function i has completed execution:
function i() {
var x = 'mochacchino'
return function j() {
console.log('Printing the value of x, from within function j: ', x)
}
}
const k = i()
setTimeout(k, 500) // invoke k (which is j) after 500ms
In a closure, the variables in the outer lexical environment themselves are available, not copies.
function l() {
var y = 'vanilla';
return {
setY: function(value) {
y = value;
},
logY: function(value) {
console.log('The value of y is: ', y);
}
}
}
const o = l()
o.logY() // The value of y is: vanilla
o.setY('chocolate')
o.logY() // The value of y is: chocolate
The chain of lexical environments, linked between execution contexts via outer environment references, forms a scope chain and defines the identifiers visible from any given function.
Please note that in an attempt to improve clarity and accuracy, this answer has been substantially changed from the original.
OK, 6-year-old closures fan. Do you want to hear the simplest example of closure?
Let's imagine the next situation: a driver is sitting in a car. That car is inside a plane. Plane is in the airport. The ability of driver to access things outside his car, but inside the plane, even if that plane leaves an airport, is a closure. That's it. When you turn 27, look at the more detailed explanation or at the example below.
Here is how I can convert my plane story into the code.
var plane = function(defaultAirport) {
var lastAirportLeft = defaultAirport;
var car = {
driver: {
startAccessPlaneInfo: function() {
setInterval(function() {
console.log("Last airport was " + lastAirportLeft);
}, 2000);
}
}
};
car.driver.startAccessPlaneInfo();
return {
leaveTheAirport: function(airPortName) {
lastAirportLeft = airPortName;
}
}
}("Boryspil International Airport");
plane.leaveTheAirport("John F. Kennedy");
This is an attempt to clear up several (possible) misunderstandings about closures that appear in some of the other answers.
A closure is not only created when you return an inner function. In fact, the enclosing function does not need to return at all in order for its closure to be created. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be called immediately or any time later. Therefore, the closure of the enclosing function is probably created as soon as the enclosing function is called since any inner function has access to that closure whenever the inner function is called, before or after the enclosing function returns.
A closure does not reference a copy of the old values of variables in its scope. The variables themselves are part of the closure, and so the value seen when accessing one of those variables is the latest value at the time it is accessed. This is why inner functions created inside of loops can be tricky, since each one has access to the same outer variables rather than grabbing a copy of the variables at the time the function is created or called.
The "variables" in a closure include any named functions declared within the function. They also include arguments of the function. A closure also has access to its containing closure's variables, all the way up to the global scope.
Closures use memory, but they don't cause memory leaks since JavaScript by itself cleans up its own circular structures that are not referenced. Internet Explorer memory leaks involving closures are created when it fails to disconnect DOM attribute values that reference closures, thus maintaining references to possibly circular structures.
I wrote a blog post a while back explaining closures. Here's what I said about closures in terms of why you'd want one.
Closures are a way to let a function
have persistent, private variables -
that is, variables that only one
function knows about, where it can
keep track of info from previous times
that it was run.
In that sense, they let a function act a bit like an object with private attributes.
Full post:
So what are these closure thingys?
The original question had a quote:
If you can't explain it to a six-year old, you really don't understand it yourself.
This is how I'd try to explain it to an actual six-year-old:
You know how grown-ups can own a house, and they call it home? When a mom has a child, the child doesn't really own anything, right? But its parents own a house, so whenever someone asks "Where's your home?", the child can answer "that house!", and point to the house of its parents.
A "Closure" is the ability of the child to always (even if abroad) be able to refer to its home, even though it's really the parent's who own the house.
Closures are simple:
The following simple example covers all the main points of JavaScript closures.*
Here is a factory that produces calculators that can add and multiply:
function make_calculator() {
var n = 0; // this calculator stores a single number n
return {
add: function(a) {
n += a;
return n;
},
multiply: function(a) {
n *= a;
return n;
}
};
}
first_calculator = make_calculator();
second_calculator = make_calculator();
first_calculator.add(3); // returns 3
second_calculator.add(400); // returns 400
first_calculator.multiply(11); // returns 33
second_calculator.multiply(10); // returns 4000
The key point: Each call to make_calculator creates a new local variable n, which continues to be usable by that calculator's add and multiply functions long after make_calculator returns.
If you are familiar with stack frames, these calculators seem strange: How can they keep accessing n after make_calculator returns? The answer is to imagine that JavaScript doesn't use "stack frames", but instead uses "heap frames", which can persist after the function call that made them returns.
Inner functions like add and multiply, which access variables declared in an outer function**, are called closures.
That is pretty much all there is to closures.
* For example, it covers all the points in the "Closures for Dummies" article given in another answer, except example 6, which simply shows that variables can be used before they are declared, a nice fact to know but completely unrelated to closures. It also covers all the points in the accepted answer, except for the points (1) that functions copy their arguments into local variables (the named function arguments), and (2) that copying numbers creates a new number, but copying an object reference gives you another reference to the same object. These are also good to know but again completely unrelated to closures. It is also very similar to the example in this answer but a bit shorter and less abstract. It does not cover the point of this answer or this comment, which is that JavaScript makes it difficult to plug the current value of a loop variable into your inner function: The "plugging in" step can only be done with a helper function that encloses your inner function and is invoked on each loop iteration. (Strictly speaking, the inner function accesses the helper function's copy of the variable, rather than having anything plugged in.) Again, very useful when creating closures, but not part of what a closure is or how it works. There is additional confusion due to closures working differently in functional languages like ML, where variables are bound to values rather than to storage space, providing a constant stream of people who understand closures in a way (namely the "plugging in" way) that is simply incorrect for JavaScript, where variables are always bound to storage space, and never to values.
** Any outer function, if several are nested, or even in the global context, as this answer points out clearly.
Can you explain closures to a 5-year-old?*
I still think Google's explanation works very well and is concise:
/*
* When a function is defined in another function and it
* has access to the outer function's context even after
* the outer function returns.
*
* An important concept to learn in JavaScript.
*/
function outerFunction(someNum) {
var someString = 'Hey!';
var content = document.getElementById('content');
function innerFunction() {
content.innerHTML = someNum + ': ' + someString;
content = null; // Internet Explorer memory leak for DOM reference
}
innerFunction();
}
outerFunction(1);​
*A C# question
I tend to learn better by GOOD/BAD comparisons. I like to see working code followed by non-working code that someone is likely to encounter. I put together a jsFiddle that does a comparison and tries to boil down the differences to the simplest explanations I could come up with.
Closures done right:
console.log('CLOSURES DONE RIGHT');
var arr = [];
function createClosure(n) {
return function () {
return 'n = ' + n;
}
}
for (var index = 0; index < 10; index++) {
arr[index] = createClosure(index);
}
for (var index of arr) {
console.log(arr[index]());
}
In the above code createClosure(n) is invoked in every iteration of the loop. Note that I named the variable n to highlight that it is a new variable created in a new function scope and is not the same variable as index which is bound to the outer scope.
This creates a new scope and n is bound to that scope; this means we have 10 separate scopes, one for each iteration.
createClosure(n) returns a function that returns the n within that scope.
Within each scope n is bound to whatever value it had when createClosure(n) was invoked so the nested function that gets returned will always return the value of n that it had when createClosure(n) was invoked.
Closures done wrong:
console.log('CLOSURES DONE WRONG');
function createClosureArray() {
var badArr = [];
for (var index = 0; index < 10; index++) {
badArr[index] = function () {
return 'n = ' + index;
};
}
return badArr;
}
var badArr = createClosureArray();
for (var index of badArr) {
console.log(badArr[index]());
}
In the above code the loop was moved within the createClosureArray() function and the function now just returns the completed array, which at first glance seems more intuitive.
What might not be obvious is that since createClosureArray() is only invoked once only one scope is created for this function instead of one for every iteration of the loop.
Within this function a variable named index is defined. The loop runs and adds functions to the array that return index. Note that index is defined within the createClosureArray function which only ever gets invoked one time.
Because there was only one scope within the createClosureArray() function, index is only bound to a value within that scope. In other words, each time the loop changes the value of index, it changes it for everything that references it within that scope.
All of the functions added to the array return the SAME index variable from the parent scope where it was defined instead of 10 different ones from 10 different scopes like the first example. The end result is that all 10 functions return the same variable from the same scope.
After the loop finished and index was done being modified the end value was 10, therefore every function added to the array returns the value of the single index variable which is now set to 10.
Result
CLOSURES DONE RIGHT
n = 0
n = 1
n = 2
n = 3
n = 4
n = 5
n = 6
n = 7
n = 8
n = 9
CLOSURES DONE WRONG
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
n = 10
Wikipedia on closures:
In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.
Technically, in JavaScript, every function is a closure. It always has an access to variables defined in the surrounding scope.
Since scope-defining construction in JavaScript is a function, not a code block like in many other languages, what we usually mean by closure in JavaScript is a function working with nonlocal variables defined in already executed surrounding function.
Closures are often used for creating functions with some hidden private data (but it's not always the case).
var db = (function() {
// Create a hidden object, which will hold the data
// it's inaccessible from the outside.
var data = {};
// Make a function, which will provide some access to the data.
return function(key, val) {
if (val === undefined) { return data[key] } // Get
else { return data[key] = val } // Set
}
// We are calling the anonymous surrounding function,
// returning the above inner function, which is a closure.
})();
db('x') // -> undefined
db('x', 1) // Set x to 1
db('x') // -> 1
// It's impossible to access the data object itself.
// We are able to get or set individual it.
ems
The example above is using an anonymous function, which was executed once. But it does not have to be. It can be named (e.g. mkdb) and executed later, generating a database function each time it is invoked. Every generated function will have its own hidden database object. Another usage example of closures is when we don't return a function, but an object containing multiple functions for different purposes, each of those function having access to the same data.
The children will never forget the secrets they have shared with their parents, even after their parents are
gone. This is what closures are for functions.
The secrets for JavaScript functions are the private variables
var parent = function() {
var name = "Mary"; // secret
}
Every time you call it, the local variable "name" is created and given the name "Mary". And every time the function exits the variable is lost and the name is forgotten.
As you may guess, because the variables are re-created every time the function is called, and nobody else will know them, there must be a secret place where they are stored. It could be called Chamber of Secrets or stack or local scope but it doesn't matter. We know they are there, somewhere, hidden in the memory.
But, in JavaScript, there is this very special thing that functions which are created inside other functions, can also know the local variables of their parents and keep them as long as they live.
var parent = function() {
var name = "Mary";
var child = function(childName) {
// I can also see that "name" is "Mary"
}
}
So, as long as we are in the parent -function, it can create one or more child functions which do share the secret variables from the secret place.
But the sad thing is, if the child is also a private variable of its parent function, it would also die when the parent ends, and the secrets would die with them.
So to live, the child has to leave before it's too late
var parent = function() {
var name = "Mary";
var child = function(childName) {
return "My name is " + childName +", child of " + name;
}
return child; // child leaves the parent ->
}
var child = parent(); // < - and here it is outside
And now, even though Mary is "no longer running", the memory of her is not lost and her child will always remember her name and other secrets they shared during their time together.
So, if you call the child "Alice", she will respond
child("Alice") => "My name is Alice, child of Mary"
That's all there is to tell.
I put together an interactive JavaScript tutorial to explain how closures work.
What's a Closure?
Here's one of the examples:
var create = function (x) {
var f = function () {
return x; // We can refer to x here!
};
return f;
};
// 'create' takes one argument, creates a function
var g = create(42);
// g is a function that takes no arguments now
var y = g();
// y is 42 here
I do not understand why the answers are so complex here.
Here is a closure:
var a = 42;
function b() { return a; }
Yes. You probably use that many times a day.
There is no reason to believe closures are a complex design hack to address specific problems. No, closures are just about using a variable that comes from a higher scope from the perspective of where the function was declared (not run).
Now what it allows you to do can be more spectacular, see other answers.
A closure is where an inner function has access to variables in its outer function. That's probably the simplest one-line explanation you can get for closures.
Example for the first point by dlaliberte:
A closure is not only created when you return an inner function. In fact, the enclosing function does not need to return at all. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be used immediately. Therefore, the closure of the enclosing function probably already exists at the time that enclosing function was called since any inner function has access to it as soon as it is called.
var i;
function foo(x) {
var tmp = 3;
i = function (y) {
console.log(x + y + (++tmp));
}
}
foo(2);
i(3);
I know there are plenty of solutions already, but I guess that this small and simple script can be useful to demonstrate the concept:
// makeSequencer will return a "sequencer" function
var makeSequencer = function() {
var _count = 0; // not accessible outside this function
var sequencer = function () {
return _count++;
}
return sequencer;
}
var fnext = makeSequencer();
var v0 = fnext(); // v0 = 0;
var v1 = fnext(); // v1 = 1;
var vz = fnext._count // vz = undefined
You're having a sleep over and you invite Dan.
You tell Dan to bring one XBox controller.
Dan invites Paul.
Dan asks Paul to bring one controller. How many controllers were brought to the party?
function sleepOver(howManyControllersToBring) {
var numberOfDansControllers = howManyControllersToBring;
return function danInvitedPaul(numberOfPaulsControllers) {
var totalControllers = numberOfDansControllers + numberOfPaulsControllers;
return totalControllers;
}
}
var howManyControllersToBring = 1;
var inviteDan = sleepOver(howManyControllersToBring);
// The only reason Paul was invited is because Dan was invited.
// So we set Paul's invitation = Dan's invitation.
var danInvitedPaul = inviteDan(howManyControllersToBring);
alert("There were " + danInvitedPaul + " controllers brought to the party.");
The author of Closures has explained closures pretty well, explaining the reason why we need them and also explaining LexicalEnvironment which is necessary to understanding closures.
Here is the summary:
What if a variable is accessed, but it isn’t local? Like here:
In this case, the interpreter finds the variable in the
outer LexicalEnvironment object.
The process consists of two steps:
First, when a function f is created, it is not created in an empty
space. There is a current LexicalEnvironment object. In the case
above, it’s window (a is undefined at the time of function
creation).
When a function is created, it gets a hidden property, named [[Scope]], which references the current LexicalEnvironment.
If a variable is read, but can not be found anywhere, an error is generated.
Nested functions
Functions can be nested one inside another, forming a chain of LexicalEnvironments which can also be called a scope chain.
So, function g has access to g, a and f.
Closures
A nested function may continue to live after the outer function has finished:
Marking up LexicalEnvironments:
As we see, this.say is a property in the user object, so it continues to live after User completed.
And if you remember, when this.say is created, it (as every function) gets an internal reference this.say.[[Scope]] to the current LexicalEnvironment. So, the LexicalEnvironment of the current User execution stays in memory. All variables of User also are its properties, so they are also carefully kept, not junked as usually.
The whole point is to ensure that if the inner function wants to access an outer variable in the future, it is able to do so.
To summarize:
The inner function keeps a reference to the outer
LexicalEnvironment.
The inner function may access variables from it
any time even if the outer function is finished.
The browser keeps the LexicalEnvironment and all its properties (variables) in memory until there is an inner function which references it.
This is called a closure.
JavaScript functions can access their:
Arguments
Locals (that is, their local variables and local functions)
Environment, which includes:
globals, including the DOM
anything in outer functions
If a function accesses its environment, then the function is a closure.
Note that outer functions are not required, though they do offer benefits I don't discuss here. By accessing data in its environment, a closure keeps that data alive. In the subcase of outer/inner functions, an outer function can create local data and eventually exit, and yet, if any inner function(s) survive after the outer function exits, then the inner function(s) keep the outer function's local data alive.
Example of a closure that uses the global environment:
Imagine that the Stack Overflow Vote-Up and Vote-Down button events are implemented as closures, voteUp_click and voteDown_click, that have access to external variables isVotedUp and isVotedDown, which are defined globally. (For simplicity's sake, I am referring to StackOverflow's Question Vote buttons, not the array of Answer Vote buttons.)
When the user clicks the VoteUp button, the voteUp_click function checks whether isVotedDown == true to determine whether to vote up or merely cancel a down vote. Function voteUp_click is a closure because it is accessing its environment.
var isVotedUp = false;
var isVotedDown = false;
function voteUp_click() {
if (isVotedUp)
return;
else if (isVotedDown)
SetDownVote(false);
else
SetUpVote(true);
}
function voteDown_click() {
if (isVotedDown)
return;
else if (isVotedUp)
SetUpVote(false);
else
SetDownVote(true);
}
function SetUpVote(status) {
isVotedUp = status;
// Do some CSS stuff to Vote-Up button
}
function SetDownVote(status) {
isVotedDown = status;
// Do some CSS stuff to Vote-Down button
}
All four of these functions are closures as they all access their environment.
As a father of a 6-year-old, currently teaching young children (and a relative novice to coding with no formal education so corrections will be required), I think the lesson would stick best through hands-on play. If the 6-year-old is ready to understand what a closure is, then they are old enough to have a go themselves. I'd suggest pasting the code into jsfiddle.net, explaining a bit, and leaving them alone to concoct a unique song. The explanatory text below is probably more appropriate for a 10 year old.
function sing(person) {
var firstPart = "There was " + person + " who swallowed ";
var fly = function() {
var creature = "a fly";
var result = "Perhaps she'll die";
alert(firstPart + creature + "\n" + result);
};
var spider = function() {
var creature = "a spider";
var result = "that wiggled and jiggled and tickled inside her";
alert(firstPart + creature + "\n" + result);
};
var bird = function() {
var creature = "a bird";
var result = "How absurd!";
alert(firstPart + creature + "\n" + result);
};
var cat = function() {
var creature = "a cat";
var result = "Imagine That!";
alert(firstPart + creature + "\n" + result);
};
fly();
spider();
bird();
cat();
}
var person="an old lady";
sing(person);
INSTRUCTIONS
DATA: Data is a collection of facts. It can be numbers, words, measurements, observations or even just descriptions of things. You can't touch it, smell it or taste it. You can write it down, speak it and hear it. You could use it to create touch smell and taste using a computer. It can be made useful by a computer using code.
CODE: All the writing above is called code. It is written in JavaScript.
JAVASCRIPT: JavaScript is a language. Like English or French or Chinese are languages. There are lots of languages that are understood by computers and other electronic processors. For JavaScript to be understood by a computer it needs an interpreter. Imagine if a teacher who only speaks Russian comes to teach your class at school. When the teacher says "все садятся", the class would not understand. But luckily you have a Russian pupil in your class who tells everyone this means "everybody sit down" - so you all do. The class is like a computer and the Russian pupil is the interpreter. For JavaScript the most common interpreter is called a browser.
BROWSER: When you connect to the Internet on a computer, tablet or phone to visit a website, you use a browser. Examples you may know are Internet Explorer, Chrome, Firefox and Safari. The browser can understand JavaScript and tell the computer what it needs to do. The JavaScript instructions are called functions.
FUNCTION: A function in JavaScript is like a factory. It might be a little factory with only one machine inside. Or it might contain many other little factories, each with many machines doing different jobs. In a real life clothes factory you might have reams of cloth and bobbins of thread going in and T-shirts and jeans coming out. Our JavaScript factory only processes data, it can't sew, drill a hole or melt metal. In our JavaScript factory data goes in and data comes out.
All this data stuff sounds a bit boring, but it is really very cool; we might have a function that tells a robot what to make for dinner. Let's say I invite you and your friend to my house. You like chicken legs best, I like sausages, your friend always wants what you want and my friend does not eat meat.
I haven't got time to go shopping, so the function needs to know what we have in the fridge to make decisions. Each ingredient has a different cooking time and we want everything to be served hot by the robot at the same time. We need to provide the function with the data about what we like, the function could 'talk' to the fridge, and the function could control the robot.
A function normally has a name, parentheses and braces. Like this:
function cookMeal() { /* STUFF INSIDE THE FUNCTION */ }
Note that /*...*/ and // stop code being read by the browser.
NAME: You can call a function just about whatever word you want. The example "cookMeal" is typical in joining two words together and giving the second one a capital letter at the beginning - but this is not necessary. It can't have a space in it, and it can't be a number on its own.
PARENTHESES: "Parentheses" or () are the letter box on the JavaScript function factory's door or a post box in the street for sending packets of information to the factory. Sometimes the postbox might be marked for example cookMeal(you, me, yourFriend, myFriend, fridge, dinnerTime), in which case you know what data you have to give it.
BRACES: "Braces" which look like this {} are the tinted windows of our factory. From inside the factory you can see out, but from the outside you can't see in.
THE LONG CODE EXAMPLE ABOVE
Our code begins with the word function, so we know that it is one! Then the name of the function sing - that's my own description of what the function is about. Then parentheses (). The parentheses are always there for a function. Sometimes they are empty, and sometimes they have something in. This one has a word in: (person). After this there is a brace like this { . This marks the start of the function sing(). It has a partner which marks the end of sing() like this }
function sing(person) { /* STUFF INSIDE THE FUNCTION */ }
So this function might have something to do with singing, and might need some data about a person. It has instructions inside to do something with that data.
Now, after the function sing(), near the end of the code is the line
var person="an old lady";
VARIABLE: The letters var stand for "variable". A variable is like an envelope. On the outside this envelope is marked "person". On the inside it contains a slip of paper with the information our function needs, some letters and spaces joined together like a piece of string (it's called a string) that make a phrase reading "an old lady". Our envelope could contain other kinds of things like numbers (called integers), instructions (called functions), lists (called arrays). Because this variable is written outside of all the braces {}, and because you can see out through the tinted windows when you are inside the braces, this variable can be seen from anywhere in the code. We call this a 'global variable'.
GLOBAL VARIABLE: person is a global variable, meaning that if you change its value from "an old lady" to "a young man", the person will keep being a young man until you decide to change it again and that any other function in the code can see that it's a young man. Press the F12 button or look at the Options settings to open the developer console of a browser and type "person" to see what this value is. Type person="a young man" to change it and then type "person" again to see that it has changed.
After this we have the line
sing(person);
This line is calling the function, as if it were calling a dog
"Come on sing, Come and get person!"
When the browser has loaded the JavaScript code an reached this line, it will start the function. I put the line at the end to make sure that the browser has all the information it needs to run it.
Functions define actions - the main function is about singing. It contains a variable called firstPart which applies to the singing about the person that applies to each of the verses of the song: "There was " + person + " who swallowed". If you type firstPart into the console, you won't get an answer because the variable is locked up in a function - the browser can't see inside the tinted windows of the braces.
CLOSURES: The closures are the smaller functions that are inside the big sing() function. The little factories inside the big factory. They each have their own braces which mean that the variables inside them can't be seen from the outside. That's why the names of the variables (creature and result) can be repeated in the closures but with different values. If you type these variable names in the console window, you won't get its value because it's hidden by two layers of tinted windows.
The closures all know what the sing() function's variable called firstPart is, because they can see out from their tinted windows.
After the closures come the lines
fly();
spider();
bird();
cat();
The sing() function will call each of these functions in the order they are given. Then the sing() function's work will be done.
Okay, talking with a 6-year old child, I would possibly use following associations.
Imagine - you are playing with your little brothers and sisters in the entire house, and you are moving around with your toys and brought some of them into your older brother's room. After a while your brother returned from the school and went to his room, and he locked inside it, so now you could not access toys left there anymore in a direct way. But you could knock the door and ask your brother for that toys. This is called toy's closure; your brother made it up for you, and he is now into outer scope.
Compare with a situation when a door was locked by draft and nobody inside (general function execution), and then some local fire occur and burn down the room (garbage collector:D), and then a new room was build and now you may leave another toys there (new function instance), but never get the same toys which were left in the first room instance.
For an advanced child I would put something like the following. It is not perfect, but it makes you feel about what it is:
function playingInBrothersRoom (withToys) {
// We closure toys which we played in the brother's room. When he come back and lock the door
// your brother is supposed to be into the outer [[scope]] object now. Thanks god you could communicate with him.
var closureToys = withToys || [],
returnToy, countIt, toy; // Just another closure helpers, for brother's inner use.
var brotherGivesToyBack = function (toy) {
// New request. There is not yet closureToys on brother's hand yet. Give him a time.
returnToy = null;
if (toy && closureToys.length > 0) { // If we ask for a specific toy, the brother is going to search for it.
for ( countIt = closureToys.length; countIt; countIt--) {
if (closureToys[countIt - 1] == toy) {
returnToy = 'Take your ' + closureToys.splice(countIt - 1, 1) + ', little boy!';
break;
}
}
returnToy = returnToy || 'Hey, I could not find any ' + toy + ' here. Look for it in another room.';
}
else if (closureToys.length > 0) { // Otherwise, just give back everything he has in the room.
returnToy = 'Behold! ' + closureToys.join(', ') + '.';
closureToys = [];
}
else {
returnToy = 'Hey, lil shrimp, I gave you everything!';
}
console.log(returnToy);
}
return brotherGivesToyBack;
}
// You are playing in the house, including the brother's room.
var toys = ['teddybear', 'car', 'jumpingrope'],
askBrotherForClosuredToy = playingInBrothersRoom(toys);
// The door is locked, and the brother came from the school. You could not cheat and take it out directly.
console.log(askBrotherForClosuredToy.closureToys); // Undefined
// But you could ask your brother politely, to give it back.
askBrotherForClosuredToy('teddybear'); // Hooray, here it is, teddybear
askBrotherForClosuredToy('ball'); // The brother would not be able to find it.
askBrotherForClosuredToy(); // The brother gives you all the rest
askBrotherForClosuredToy(); // Nothing left in there
As you can see, the toys left in the room are still accessible via the brother and no matter if the room is locked. Here is a jsbin to play around with it.
A function in JavaScript is not just a reference to a set of instructions (as in C language), but it also includes a hidden data structure which is composed of references to all nonlocal variables it uses (captured variables). Such two-piece functions are called closures. Every function in JavaScript can be considered a closure.
Closures are functions with a state. It is somewhat similar to "this" in the sense that "this" also provides state for a function but function and "this" are separate objects ("this" is just a fancy parameter, and the only way to bind it permanently to a function is to create a closure). While "this" and function always live separately, a function cannot be separated from its closure and the language provides no means to access captured variables.
Because all these external variables referenced by a lexically nested function are actually local variables in the chain of its lexically enclosing functions (global variables can be assumed to be local variables of some root function), and every single execution of a function creates new instances of its local variables, it follows that every execution of a function returning (or otherwise transferring it out, such as registering it as a callback) a nested function creates a new closure (with its own potentially unique set of referenced nonlocal variables which represent its execution context).
Also, it must be understood that local variables in JavaScript are created not on the stack frame, but on the heap and destroyed only when no one is referencing them. When a function returns, references to its local variables are decremented, but they can still be non-null if during the current execution they became part of a closure and are still referenced by its lexically nested functions (which can happen only if the references to these nested functions were returned or otherwise transferred to some external code).
An example:
function foo (initValue) {
//This variable is not destroyed when the foo function exits.
//It is 'captured' by the two nested functions returned below.
var value = initValue;
//Note that the two returned functions are created right now.
//If the foo function is called again, it will return
//new functions referencing a different 'value' variable.
return {
getValue: function () { return value; },
setValue: function (newValue) { value = newValue; }
}
}
function bar () {
//foo sets its local variable 'value' to 5 and returns an object with
//two functions still referencing that local variable
var obj = foo(5);
//Extracting functions just to show that no 'this' is involved here
var getValue = obj.getValue;
var setValue = obj.setValue;
alert(getValue()); //Displays 5
setValue(10);
alert(getValue()); //Displays 10
//At this point getValue and setValue functions are destroyed
//(in reality they are destroyed at the next iteration of the garbage collector).
//The local variable 'value' in the foo is no longer referenced by
//anything and is destroyed too.
}
bar();
An answer for a six-year-old (assuming he knows what a function is and what a variable is, and what data is):
Functions can return data. One kind of data you can return from a function is another function. When that new function gets returned, all the variables and arguments used in the function that created it don't go away. Instead, that parent function "closes." In other words, nothing can look inside of it and see the variables it used except for the function it returned. That new function has a special ability to look back inside the function that created it and see the data inside of it.
function the_closure() {
var x = 4;
return function () {
return x; // Here, we look back inside the_closure for the value of x
}
}
var myFn = the_closure();
myFn(); //=> 4
Another really simple way to explain it is in terms of scope:
Any time you create a smaller scope inside of a larger scope, the smaller scope will always be able to see what is in the larger scope.
Perhaps a little beyond all but the most precocious of six-year-olds, but a few examples that helped make the concept of closure in JavaScript click for me.
A closure is a function that has access to another function's scope (its variables and functions). The easiest way to create a closure is with a function within a function; the reason being that in JavaScript a function always has access to its containing function’s scope.
function outerFunction() {
var outerVar = "monkey";
function innerFunction() {
alert(outerVar);
}
innerFunction();
}
outerFunction();
ALERT: monkey
In the above example, outerFunction is called which in turn calls innerFunction. Note how outerVar is available to innerFunction, evidenced by its correctly alerting the value of outerVar.
Now consider the following:
function outerFunction() {
var outerVar = "monkey";
function innerFunction() {
return outerVar;
}
return innerFunction;
}
var referenceToInnerFunction = outerFunction();
alert(referenceToInnerFunction());
ALERT: monkey
referenceToInnerFunction is set to outerFunction(), which simply returns a reference to innerFunction. When referenceToInnerFunction is called, it returns outerVar. Again, as above, this demonstrates that innerFunction has access to outerVar, a variable of outerFunction. Furthermore, it is interesting to note that it retains this access even after outerFunction has finished executing.
And here is where things get really interesting. If we were to get rid of outerFunction, say set it to null, you might think that referenceToInnerFunction would loose its access to the value of outerVar. But this is not the case.
function outerFunction() {
var outerVar = "monkey";
function innerFunction() {
return outerVar;
}
return innerFunction;
}
var referenceToInnerFunction = outerFunction();
alert(referenceToInnerFunction());
outerFunction = null;
alert(referenceToInnerFunction());
ALERT: monkey
ALERT: monkey
But how is this so? How can referenceToInnerFunction still know the value of outerVar now that outerFunction has been set to null?
The reason that referenceToInnerFunction can still access the value of outerVar is because when the closure was first created by placing innerFunction inside of outerFunction, innerFunction added a reference to outerFunction’s scope (its variables and functions) to its scope chain. What this means is that innerFunction has a pointer or reference to all of outerFunction’s variables, including outerVar. So even when outerFunction has finished executing, or even if it is deleted or set to null, the variables in its scope, like outerVar, stick around in memory because of the outstanding reference to them on the part of the innerFunction that has been returned to referenceToInnerFunction. To truly release outerVar and the rest of outerFunction’s variables from memory you would have to get rid of this outstanding reference to them, say by setting referenceToInnerFunction to null as well.
//////////
Two other things about closures to note. First, the closure will always have access to the last values of its containing function.
function outerFunction() {
var outerVar = "monkey";
function innerFunction() {
alert(outerVar);
}
outerVar = "gorilla";
innerFunction();
}
outerFunction();
ALERT: gorilla
Second, when a closure is created, it retains a reference to all of its enclosing function’s variables and functions; it doesn’t get to pick and choose. And but so, closures should be used sparingly, or at least carefully, as they can be memory intensive; a lot of variables can be kept in memory long after a containing function has finished executing.
I'd simply point them to the Mozilla Closures page. It's the best, most concise and simple explanation of closure basics and practical usage that I've found. It is highly recommended to anyone learning JavaScript.
And yes, I'd even recommend it to a 6-year old -- if the 6-year old is learning about closures, then it's logical they're ready to comprehend the concise and simple explanation provided in the article.

React Class Component setState [duplicate]

I am looking to find a clear explanation of what the "this" keyword does, and how to use it correctly.
It seems to behave strangely, and I don't fully understand why.
How does this work and when should it be used?
this is a keyword in JavaScript that is a property of an execution context. Its main use is in functions and constructors.
The rules for this are quite simple (if you stick to best practices).
Technical description of this in the specification
The ECMAScript standard defines this via the abstract operation (abbreviated AO) ResolveThisBinding:
The [AO] ResolveThisBinding […] determines the binding of the keyword this using the LexicalEnvironment of the running execution context. [Steps]:
Let envRec be GetThisEnvironment().
Return ? envRec.GetThisBinding().
Global Environment Records, module Environment Records, and function Environment Records each have their own GetThisBinding method.
The GetThisEnvironment AO finds the current running execution context’s LexicalEnvironment and finds the closest ascendant Environment Record (by iteratively accessing their [[OuterEnv]] properties) which has a this binding (i.e. HasThisBinding returns true). This process ends in one of the three Environment Record types.
The value of this often depends on whether code is in strict mode.
The return value of GetThisBinding reflects the value of this of the current execution context, so whenever a new execution context is established, this resolves to a distinct value. This can also happen when the current execution context is modified. The following subsections list the five cases where this can happen.
You can put the code samples in the AST explorer to follow along with specification details.
1. Global execution context in scripts
This is script code evaluated at the top level, e.g. directly inside a <script>:
<script>
// Global context
console.log(this); // Logs global object.
setTimeout(function(){
console.log("Not global context");
});
</script>
When in the initial global execution context of a script, evaluating this causes GetThisBinding to take the following steps:
The GetThisBinding concrete method of a global Environment Record envRec […] [does this]:
Return envRec.[[GlobalThisValue]].
The [[GlobalThisValue]] property of a global Environment Record is always set to the host-defined global object, which is reachable via globalThis (window on Web, global on Node.js; Docs on MDN). Follow the steps of InitializeHostDefinedRealm to learn how the [[GlobalThisValue]] property comes to be.
2. Global execution context in modules
Modules have been introduced in ECMAScript 2015.
This applies to modules, e.g. when directly inside a <script type="module">, as opposed to a simple <script>.
When in the initial global execution context of a module, evaluating this causes GetThisBinding to take the following steps:
The GetThisBinding concrete method of a module Environment Record […] [does this]:
Return undefined.
In modules, the value of this is always undefined in the global context. Modules are implicitly in strict mode.
3. Entering eval code
There are two kinds of eval calls: direct and indirect. This distinction exists since the ECMAScript 5th edition.
A direct eval call usually looks like eval(…); or (eval)(…); (or ((eval))(…);, etc.).1 It’s only direct if the call expression fits a narrow pattern.2
An indirect eval call involves calling the function reference eval in any other way. It could be eval?.(…), (…, eval)(…), window.eval(…), eval.call(…,…), etc. Given const aliasEval1 = eval; window.aliasEval2 = eval;, it would also be aliasEval1(…), aliasEval2(…). Separately, given const originalEval = eval; window.eval = (x) => originalEval(x);, calling eval(…) would also be indirect.
See chuckj’s answer to “(1, eval)('this') vs eval('this') in JavaScript?” and Dmitry Soshnikov’s ECMA-262-5 in detail – Chapter 2: Strict Mode (archived) for when you might use an indirect eval() call.
PerformEval executes the eval code. It creates a new declarative Environment Record as its LexicalEnvironment, which is where GetThisEnvironment gets the this value from.
Then, if this appears in eval code, the GetThisBinding method of the Environment Record found by GetThisEnvironment is called and its value returned.
And the created declarative Environment Record depends on whether the eval call was direct or indirect:
In a direct eval, it will be based on the current running execution context’s LexicalEnvironment.
In an indirect eval, it will be based on the [[GlobalEnv]] property (a global Environment Record) of the Realm Record which executed the indirect eval.
Which means:
In a direct eval, the this value doesn’t change; it’s taken from the lexical scope that called eval.
In an indirect eval, the this value is the global object (globalThis).
What about new Function? — new Function is similar to eval, but it doesn’t call the code immediately; it creates a function. A this binding doesn’t apply anywhere here, except when the function is called, which works normally, as explained in the next subsection.
4. Entering function code
Entering function code occurs when calling a function.
There are four categories of syntax to invoke a function.
The EvaluateCall AO is performed for these three:3
Normal function calls
Optional chaining calls
Tagged templates
And EvaluateNew is performed for this one:3
Constructor invocations
The actual function call happens at the Call AO, which is called with a thisValue determined from context; this argument is passed along in a long chain of call-related calls. Call calls the [[Call]] internal slot of the function. This calls PrepareForOrdinaryCall where a new function Environment Record is created:
A function Environment Record is a declarative Environment Record that is used to represent the top-level scope of a function and, if the function is not an ArrowFunction, provides a this binding. If a function is not an ArrowFunction function and references super, its function Environment Record also contains the state that is used to perform super method invocations from within the function.
In addition, there is the [[ThisValue]] field in a function Environment Record:
This is the this value used for this invocation of the function.
The NewFunctionEnvironment call also sets the function environment’s [[ThisBindingStatus]] property.
[[Call]] also calls OrdinaryCallBindThis, where the appropriate thisArgument is determined based on:
the original reference,
the kind of the function, and
whether or not the code is in strict mode.
Once determined, a final call to the BindThisValue method of the newly created function Environment Record actually sets the [[ThisValue]] field to the thisArgument.
Finally, this very field is where a function Environment Record’s GetThisBinding AO gets the value for this from:
The GetThisBinding concrete method of a function Environment Record envRec […] [does this]:
[…]
3. Return envRec.[[ThisValue]].
Again, how exactly the this value is determined depends on many factors; this was just a general overview. With this technical background, let’s examine all the concrete examples.
Arrow functions
When an arrow function is evaluated, the [[ThisMode]] internal slot of the function object is set to “lexical” in OrdinaryFunctionCreate.
At OrdinaryCallBindThis, which takes a function F:
Let thisMode be F.[[ThisMode]].
If thisMode is lexical, return NormalCompletion(undefined).
[…]
which just means that the rest of the algorithm which binds this is skipped. An arrow function does not bind its own this value.
So, what is this inside an arrow function, then? Looking back at ResolveThisBinding and GetThisEnvironment, the HasThisBinding method explicitly returns false.
The HasThisBinding concrete method of a function Environment Record envRec […] [does this]:
If envRec.[[ThisBindingStatus]] is lexical, return false; otherwise, return true.
So the outer environment is looked up instead, iteratively. The process will end in one of the three environments that have a this binding.
This just means that, in arrow function bodies, this comes from the lexical scope of the arrow function, or in other words (from Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?):
Arrow functions don’t have their own this […] binding. Instead, [this identifier is] resolved in the lexical scope like any other variable. That means that inside an arrow function, this [refers] to the [value of this] in the environment the arrow function is defined in (i.e. “outside” the arrow function).
Function properties
In normal functions (function, methods), this is determined by how the function is called.
This is where these “syntax variants” come in handy.
Consider this object containing a function:
const refObj = {
func: function(){
console.log(this);
}
};
Alternatively:
const refObj = {
func(){
console.log(this);
}
};
In any of the following function calls, the this value inside func will be refObj.1
refObj.func()
refObj["func"]()
refObj?.func()
refObj.func?.()
refObj.func``
If the called function is syntactically a property of a base object, then this base will be the “reference” of the call, which, in usual cases, will be the value of this. This is explained by the evaluation steps linked above; for example, in refObj.func() (or refObj["func"]()), the CallMemberExpression is the entire expression refObj.func(), which consists of the MemberExpression refObj.func and the Arguments ().
But also, refObj.func and refObj play three roles, each:
they’re both expressions,
they’re both references, and
they’re both values.
refObj.func as a value is the callable function object; the corresponding reference is used to determine the this binding.
The optional chaining and tagged template examples work very similarly: basically, the reference is everything before the ?.(), before the ``, or before the ().
EvaluateCall uses IsPropertyReference of that reference to determine if it is a property of an object, syntactically. It’s trying to get the [[Base]] property of the reference (which is e.g. refObj, when applied to refObj.func; or foo.bar when applied to foo.bar.baz). If it is written as a property, then GetThisValue will get this [[Base]] property and use it as the this value.
Note: Getters / Setters work the same way as methods, regarding this. Simple properties don’t affect the execution context, e.g. here, this is in global scope:
const o = {
a: 1,
b: this.a, // Is `globalThis.a`.
[this.a]: 2 // Refers to `globalThis.a`.
};
Calls without base reference, strict mode, and with
A call without a base reference is usually a function that isn’t called as a property. For example:
func(); // As opposed to `refObj.func();`.
This also happens when passing or assigning methods, or using the comma operator. This is where the difference between Reference Record and Value is relevant.
Note function j: following the specification, you will notice that j can only return the function object (Value) itself, but not a Reference Record. Therefore the base reference refObj is lost.
const g = (f) => f(); // No base ref.
const h = refObj.func;
const j = () => refObj.func;
g(refObj.func);
h(); // No base ref.
j()(); // No base ref.
(0, refObj.func)(); // Another common pattern to remove the base ref.
EvaluateCall calls Call with a thisValue of undefined here. This makes a difference in OrdinaryCallBindThis (F: the function object; thisArgument: the thisValue passed to Call):
Let thisMode be F.[[ThisMode]].
[…]
If thisMode is strict, let thisValue be thisArgument.
Else,
If thisArgument is undefined or null, then
Let globalEnv be calleeRealm.[[GlobalEnv]].
[…]
Let thisValue be globalEnv.[[GlobalThisValue]].
Else,
Let thisValue be ! ToObject(thisArgument).
NOTE: ToObject produces wrapper objects […].
[…]
Note: step 5 sets the actual value of this to the supplied thisArgument in strict mode — undefined in this case. In “sloppy mode”, an undefined or null thisArgument results in this being the global this value.
If IsPropertyReference returns false, then EvaluateCall takes these steps:
Let refEnv be ref.[[Base]].
Assert: refEnv is an Environment Record.
Let thisValue be refEnv.WithBaseObject().
This is where an undefined thisValue may come from: refEnv.WithBaseObject() is always undefined, except in with statements. In this case, thisValue will be the binding object.
There’s also Symbol.unscopables (Docs on MDN) to control the with binding behavior.
To summarize, so far:
function f1(){
console.log(this);
}
function f2(){
console.log(this);
}
function f3(){
console.log(this);
}
const o = {
f1,
f2,
[Symbol.unscopables]: {
f2: true
}
};
f1(); // Logs `globalThis`.
with(o){
f1(); // Logs `o`.
f2(); // `f2` is unscopable, so this logs `globalThis`.
f3(); // `f3` is not on `o`, so this logs `globalThis`.
}
and:
"use strict";
function f(){
console.log(this);
}
f(); // Logs `undefined`.
// `with` statements are not allowed in strict-mode code.
Note that when evaluating this, it doesn’t matter where a normal function is defined.
.call, .apply, .bind, thisArg, and primitives
Another consequence of step 5 of OrdinaryCallBindThis, in conjunction with step 6.2 (6.b in the spec), is that a primitive this value is coerced to an object only in “sloppy” mode.
To examine this, let’s introduce another source for the this value: the three methods that override the this binding:4
Function.prototype.apply(thisArg, argArray)
Function.prototype. {call, bind} (thisArg, ...args)
.bind creates a bound function, whose this binding is set to thisArg and cannot change again. .call and .apply call the function immediately, with the this binding set to thisArg.
.call and .apply map directly to Call, using the specified thisArg. .bind creates a bound function with BoundFunctionCreate. These have their own [[Call]] method which looks up the function object’s [[BoundThis]] internal slot.
Examples of setting a custom this value:
function f(){
console.log(this);
}
const myObj = {},
g = f.bind(myObj),
h = (m) => m();
// All of these log `myObj`.
g();
f.bind(myObj)();
f.call(myObj);
h(g);
For objects, this is the same in strict and non-strict mode.
Now, try to supply a primitive value:
function f(){
console.log(this);
}
const myString = "s",
g = f.bind(myString);
g(); // Logs `String { "s" }`.
f.call(myString); // Logs `String { "s" }`.
In non-strict mode, primitives are coerced to their object-wrapped form. It’s the same kind of object you get when calling Object("s") or new String("s"). In strict mode, you can use primitives:
"use strict";
function f(){
console.log(this);
}
const myString = "s",
g = f.bind(myString);
g(); // Logs `"s"`.
f.call(myString); // Logs `"s"`.
Libraries make use of these methods, e.g. jQuery sets the this to the DOM element selected here:
$("button").click(function(){
console.log(this); // Logs the clicked button.
});
Constructors, classes, and new
When calling a function as a constructor using the new operator, EvaluateNew calls Construct, which calls the [[Construct]] method. If the function is a base constructor (i.e. not a class extends…{…}), it sets thisArgument to a new object created from the constructor’s prototype. Properties set on this in the constructor will end up on the resulting instance object. this is implicitly returned, unless you explicitly return your own non-primitive value.
A class is a new way of creating constructor functions, introduced in ECMAScript 2015.
function Old(a){
this.p = a;
}
const o = new Old(1);
console.log(o); // Logs `Old { p: 1 }`.
class New{
constructor(a){
this.p = a;
}
}
const n = new New(1);
console.log(n); // Logs `New { p: 1 }`.
Class definitions are implicitly in strict mode:
class A{
m1(){
return this;
}
m2(){
const m1 = this.m1;
console.log(m1());
}
}
new A().m2(); // Logs `undefined`.
super
The exception to the behavior with new is class extends…{…}, as mentioned above. Derived classes do not immediately set their this value upon invocation; they only do so once the base class is reached through a series of super calls (happens implicitly without an own constructor). Using this before calling super is not allowed.
Calling super calls the super constructor with the this value of the lexical scope (the function Environment Record) of the call. GetThisValue has a special rule for super calls. It uses BindThisValue to set this to that Environment Record.
class DerivedNew extends New{
constructor(a, a2){
// Using `this` before `super` results in a ReferenceError.
super(a);
this.p2 = a2;
}
}
const n2 = new DerivedNew(1, 2);
console.log(n2); // Logs `DerivedNew { p: 1, p2: 2 }`.
5. Evaluating class fields
Instance fields and static fields were introduced in ECMAScript 2022.
When a class is evaluated, ClassDefinitionEvaluation is performed, modifying the running execution context. For each ClassElement:
if a field is static, then this refers to the class itself,
if a field is not static, then this refers to the instance.
Private fields (e.g. #x) and methods are added to a PrivateEnvironment.
Static blocks are currently a TC39 stage 3 proposal. Static blocks work the same as static fields and methods: this inside them refers to the class itself.
Note that in methods and getters / setters, this works just like in normal function properties.
class Demo{
a = this;
b(){
return this;
}
static c = this;
static d(){
return this;
}
// Getters, setters, private modifiers are also possible.
}
const demo = new Demo;
console.log(demo.a, demo.b()); // Both log `demo`.
console.log(Demo.c, Demo.d()); // Both log `Demo`.
1: (o.f)() is equivalent to o.f(); (f)() is equivalent to f(). This is explained in this 2ality article (archived). Particularly see how a ParenthesizedExpression is evaluated.
2: It must be a MemberExpression, must not be a property, must have a [[ReferencedName]] of exactly "eval", and must be the %eval% intrinsic object.
3: Whenever the specification says “Let ref be the result of evaluating X.”, then X is some expression that you need to find the evaluation steps for. For example, evaluating a MemberExpression or CallExpression is the result of one of these algorithms. Some of them result in a Reference Record.
4: There are also several other native and host methods that allow providing a this value, notably Array.prototype.map, Array.prototype.forEach, etc. that accept a thisArg as their second argument. Anyone can make their own methods to alter this like (func, thisArg) => func.bind(thisArg), (func, thisArg) => func.call(thisArg), etc. As always, MDN offers great documentation.
Just for fun, test your understanding with some examples
For each code snippet, answer the question: “What is the value of this at the marked line? Why?”.
To reveal the answers, click the gray boxes.
if(true){
console.log(this); // What is `this` here?
}
globalThis. The marked line is evaluated in the initial global execution context.
const obj = {};
function myFun(){
return { // What is `this` here?
"is obj": this === obj,
"is globalThis": this === globalThis
};
}
obj.method = myFun;
console.log(obj.method());
obj. When calling a function as a property of an object, it is called with the this binding set to the base of the reference obj.method, i.e. obj.
const obj = {
myMethod: function(){
return { // What is `this` here?
"is obj": this === obj,
"is globalThis": this === globalThis
};
}
},
myFun = obj.myMethod;
console.log(myFun());
globalThis. Since the function value myFun / obj.myMethod is not called off of an object, as a property, the this binding will be globalThis.
This is different from Python, in which accessing a method (obj.myMethod) creates a bound method object.
const obj = {
myFun: () => ({ // What is `this` here?
"is obj": this === obj,
"is globalThis": this === globalThis
})
};
console.log(obj.myFun());
globalThis. Arrow functions don’t create their own this binding. The lexical scope is the same as the initial global scope, so this is globalThis.
function myFun(){
console.log(this); // What is `this` here?
}
const obj = {
myMethod: function(){
eval("myFun()");
}
};
obj.myMethod();
globalThis. When evaluating the direct eval call, this is obj. However, in the eval code, myFun is not called off of an object, so the this binding is set to the global object.
function myFun() {
// What is `this` here?
return {
"is obj": this === obj,
"is globalThis": this === globalThis
};
}
const obj = {};
console.log(myFun.call(obj));
obj. The line myFun.call(obj); is invoking the special built-in function Function.prototype.call, which accepts thisArg as the first argument.
class MyCls{
arrow = () => ({ // What is `this` here?
"is MyCls": this === MyCls,
"is globalThis": this === globalThis,
"is instance": this instanceof MyCls
});
}
console.log(new MyCls().arrow());
It’s the instance of MyCls. Arrow functions don’t change the this binding, so it comes from lexical scope. Therefore, this is exactly the same as with the class fields mentioned above, like a = this;. Try changing it to static arrow. Do you get the result you expect?
The this keyword behaves differently in JavaScript compared to other languages. In Object Oriented languages, the this keyword refers to the current instance of the class. In JavaScript the value of this is determined by the invocation context of function (context.function()) and where it is called.
1. When used in global context
When you use this in global context, it is bound to global object (window in browser)
document.write(this); //[object Window]
When you use this inside a function defined in the global context, this is still bound to global object since the function is actually made a method of global context.
function f1()
{
return this;
}
document.write(f1()); //[object Window]
Above f1 is made a method of global object. Thus we can also call it on window object as follows:
function f()
{
return this;
}
document.write(window.f()); //[object Window]
2. When used inside object method
When you use this keyword inside an object method, this is bound to the "immediate" enclosing object.
var obj = {
name: "obj",
f: function () {
return this + ":" + this.name;
}
};
document.write(obj.f()); //[object Object]:obj
Above I have put the word immediate in double quotes. It is to make the point that if you nest the object inside another object, then this is bound to the immediate parent.
var obj = {
name: "obj1",
nestedobj: {
name:"nestedobj",
f: function () {
return this + ":" + this.name;
}
}
}
document.write(obj.nestedobj.f()); //[object Object]:nestedobj
Even if you add function explicitly to the object as a method, it still follows above rules, that is this still points to the immediate parent object.
var obj1 = {
name: "obj1",
}
function returnName() {
return this + ":" + this.name;
}
obj1.f = returnName; //add method to object
document.write(obj1.f()); //[object Object]:obj1
3. When invoking context-less function
When you use this inside function that is invoked without any context (i.e. not on any object), it is bound to the global object (window in browser)(even if the function is defined inside the object) .
var context = "global";
var obj = {
context: "object",
method: function () {
function f() {
var context = "function";
return this + ":" +this.context;
};
return f(); //invoked without context
}
};
document.write(obj.method()); //[object Window]:global
Trying it all with functions
We can try above points with functions too. However there are some differences.
Above we added members to objects using object literal notation. We can add members to functions by using this. to specify them.
Object literal notation creates an instance of object which we can use immediately. With function we may need to first create its instance using new operator.
Also in an object literal approach, we can explicitly add members to already defined object using dot operator. This gets added to the specific instance only. However I have added variable to the function prototype so that it gets reflected in all instances of the function.
Below I tried out all the things that we did with Object and this above, but by first creating function instead of directly writing an object.
/*********************************************************************
1. When you add variable to the function using this keyword, it
gets added to the function prototype, thus allowing all function
instances to have their own copy of the variables added.
*********************************************************************/
function functionDef()
{
this.name = "ObjDefinition";
this.getName = function(){
return this+":"+this.name;
}
}
obj1 = new functionDef();
document.write(obj1.getName() + "<br />"); //[object Object]:ObjDefinition
/*********************************************************************
2. Members explicitly added to the function protorype also behave
as above: all function instances have their own copy of the
variable added.
*********************************************************************/
functionDef.prototype.version = 1;
functionDef.prototype.getVersion = function(){
return "v"+this.version; //see how this.version refers to the
//version variable added through
//prototype
}
document.write(obj1.getVersion() + "<br />"); //v1
/*********************************************************************
3. Illustrating that the function variables added by both above
ways have their own copies across function instances
*********************************************************************/
functionDef.prototype.incrementVersion = function(){
this.version = this.version + 1;
}
var obj2 = new functionDef();
document.write(obj2.getVersion() + "<br />"); //v1
obj2.incrementVersion(); //incrementing version in obj2
//does not affect obj1 version
document.write(obj2.getVersion() + "<br />"); //v2
document.write(obj1.getVersion() + "<br />"); //v1
/*********************************************************************
4. `this` keyword refers to the immediate parent object. If you
nest the object through function prototype, then `this` inside
object refers to the nested object not the function instance
*********************************************************************/
functionDef.prototype.nestedObj = { name: 'nestedObj',
getName1 : function(){
return this+":"+this.name;
}
};
document.write(obj2.nestedObj.getName1() + "<br />"); //[object Object]:nestedObj
/*********************************************************************
5. If the method is on an object's prototype chain, `this` refers
to the object the method was called on, as if the method was on
the object.
*********************************************************************/
var ProtoObj = { fun: function () { return this.a } };
var obj3 = Object.create(ProtoObj); //creating an object setting ProtoObj
//as its prototype
obj3.a = 999; //adding instance member to obj3
document.write(obj3.fun()+"<br />");//999
//calling obj3.fun() makes
//ProtoObj.fun() to access obj3.a as
//if fun() is defined on obj3
4. When used inside constructor function.
When the function is used as a constructor (that is when it is called with new keyword), this inside function body points to the new object being constructed.
var myname = "global context";
function SimpleFun()
{
this.myname = "simple function";
}
var obj1 = new SimpleFun(); //adds myname to obj1
//1. `new` causes `this` inside the SimpleFun() to point to the
// object being constructed thus adding any member
// created inside SimipleFun() using this.membername to the
// object being constructed
//2. And by default `new` makes function to return newly
// constructed object if no explicit return value is specified
document.write(obj1.myname); //simple function
5. When used inside function defined on prototype chain
If the method is on an object's prototype chain, this inside such method refers to the object the method was called on, as if the method is defined on the object.
var ProtoObj = {
fun: function () {
return this.a;
}
};
//Object.create() creates object with ProtoObj as its
//prototype and assigns it to obj3, thus making fun()
//to be the method on its prototype chain
var obj3 = Object.create(ProtoObj);
obj3.a = 999;
document.write(obj3.fun()); //999
//Notice that fun() is defined on obj3's prototype but
//`this.a` inside fun() retrieves obj3.a
6. Inside call(), apply() and bind() functions
All these methods are defined on Function.prototype.
These methods allows to write a function once and invoke it in different context. In other words, they allows to specify the value of this which will be used while the function is being executed. They also take any parameters to be passed to the original function when it is invoked.
fun.apply(obj1 [, argsArray]) Sets obj1 as the value of this inside fun() and calls fun() passing elements of argsArray as its arguments.
fun.call(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) - Sets obj1 as the value of this inside fun() and calls fun() passing arg1, arg2, arg3, ... as its arguments.
fun.bind(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) - Returns the reference to the function fun with this inside fun bound to obj1 and parameters of fun bound to the parameters specified arg1, arg2, arg3,....
By now the difference between apply, call and bind must have become apparent. apply allows to specify the arguments to function as array-like object i.e. an object with a numeric length property and corresponding non-negative integer properties. Whereas call allows to specify the arguments to the function directly. Both apply and call immediately invokes the function in the specified context and with the specified arguments. On the other hand, bind simply returns the function bound to the specified this value and the arguments. We can capture the reference to this returned function by assigning it to a variable and later we can call it any time.
function add(inc1, inc2)
{
return this.a + inc1 + inc2;
}
var o = { a : 4 };
document.write(add.call(o, 5, 6)+"<br />"); //15
//above add.call(o,5,6) sets `this` inside
//add() to `o` and calls add() resulting:
// this.a + inc1 + inc2 =
// `o.a` i.e. 4 + 5 + 6 = 15
document.write(add.apply(o, [5, 6]) + "<br />"); //15
// `o.a` i.e. 4 + 5 + 6 = 15
var g = add.bind(o, 5, 6); //g: `o.a` i.e. 4 + 5 + 6
document.write(g()+"<br />"); //15
var h = add.bind(o, 5); //h: `o.a` i.e. 4 + 5 + ?
document.write(h(6) + "<br />"); //15
// 4 + 5 + 6 = 15
document.write(h() + "<br />"); //NaN
//no parameter is passed to h()
//thus inc2 inside add() is `undefined`
//4 + 5 + undefined = NaN</code>
7. this inside event handlers
When you assign function directly to event handlers of an element, use of this directly inside event handling function refers to the corresponding element. Such direct function assignment can be done using addeventListener method or through the traditional event registration methods like onclick.
Similarly, when you use this directly inside the event property (like <button onclick="...this..." >) of the element, it refers to the element.
However use of this indirectly through the other function called inside the event handling function or event property resolves to the global object window.
The same above behavior is achieved when we attach the function to the event handler using Microsoft's Event Registration model method attachEvent. Instead of assigning the function to the event handler (and the thus making the function method of the element), it calls the function on the event (effectively calling it in global context).
I recommend to better try this in JSFiddle.
<script>
function clickedMe() {
alert(this + " : " + this.tagName + " : " + this.id);
}
document.getElementById("button1").addEventListener("click", clickedMe, false);
document.getElementById("button2").onclick = clickedMe;
document.getElementById("button5").attachEvent('onclick', clickedMe);
</script>
<h3>Using `this` "directly" inside event handler or event property</h3>
<button id="button1">click() "assigned" using addEventListner() </button><br />
<button id="button2">click() "assigned" using click() </button><br />
<button id="button3" onclick="alert(this+ ' : ' + this.tagName + ' : ' + this.id);">used `this` directly in click event property</button>
<h3>Using `this` "indirectly" inside event handler or event property</h3>
<button onclick="alert((function(){return this + ' : ' + this.tagName + ' : ' + this.id;})());">`this` used indirectly, inside function <br /> defined & called inside event property</button><br />
<button id="button4" onclick="clickedMe()">`this` used indirectly, inside function <br /> called inside event property</button> <br />
IE only: <button id="button5">click() "attached" using attachEvent() </button>
8. this in ES6 arrow function
In an arrow function, this will behave like common variables: it will be inherited from its lexical scope. The function's this, where the arrow function is defined, will be the arrow function's this.
So, that's the same behavior as:
(function(){}).bind(this)
See the following code:
const globalArrowFunction = () => {
return this;
};
console.log(globalArrowFunction()); //window
const contextObject = {
method1: () => {return this},
method2: function(){
return () => {return this};
}
};
console.log(contextObject.method1()); //window
const contextLessFunction = contextObject.method1;
console.log(contextLessFunction()); //window
console.log(contextObject.method2()()) //contextObject
const innerArrowFunction = contextObject.method2();
console.log(innerArrowFunction()); //contextObject
Javascript's this
Simple function invocation
Consider the following function:
function foo() {
console.log("bar");
console.log(this);
}
foo(); // calling the function
Note that we are running this in the normal mode, i.e. strict mode is not used.
When running in a browser, the value of this would be logged as window. This is because window is the global variable in a web browser's scope.
If you run this same piece of code in an environment like node.js, this would refer to the global variable in your app.
Now if we run this in strict mode by adding the statement "use strict"; to the beginning of the function declaration, this would no longer refer to the global variable in either of the environments. This is done to avoid confusions in strict mode. this would, in this case just log undefined, because that is what it is, it is not defined.
In the following cases, we would see how to manipulate the value of this.
Calling a function on an object
There are different ways to do this. If you have called native methods in Javascript like forEach and slice, you should already know that the this variable in that case refers to the Object on which you called that function (Note that in javascript, just about everything is an Object, including Arrays and Functions). Take the following code for example.
var myObj = {key: "Obj"};
myObj.logThis = function () {
// I am a method
console.log(this);
}
myObj.logThis(); // myObj is logged
If an Object contains a property which holds a Function, the property is called a method. This method, when called, will always have it's this variable set to the Object it is associated with. This is true for both strict and non-strict modes.
Note that if a method is stored (or rather, copied) in another variable, the reference to this is no longer preserved in the new variable. For example:
// continuing with the previous code snippet
var myVar = myObj.logThis;
myVar();
// logs either of window/global/undefined based on mode of operation
Considering a more commonly practical scenario:
var el = document.getElementById('idOfEl');
el.addEventListener('click', function() { console.log(this) });
// the function called by addEventListener contains this as the reference to the element
// so clicking on our element would log that element itself
The new keyword
Consider a constructor function in Javascript:
function Person (name) {
this.name = name;
this.sayHello = function () {
console.log ("Hello", this);
}
}
var awal = new Person("Awal");
awal.sayHello();
// In `awal.sayHello`, `this` contains the reference to the variable `awal`
How does this work? Well, let's see what happens when we use the new keyword.
Calling the function with the new keyword would immediately initialize an Object of type Person.
The constructor of this Object has its constructor set to Person. Also, note that typeof awal would return Object only.
This new Object would be assigned the prototype of Person.prototype. This means that any method or property in the Person prototype would be available to all instances of Person, including awal.
The function Person itself is now invoked; this being a reference to the newly constructed object awal.
Pretty straightforward, eh?
Note that the official ECMAScript spec nowhere states that such types of functions are actual constructor functions. They are just normal functions, and new can be used on any function. It's just that we use them as such, and so we call them as such only.
Calling functions on Functions: call and apply
So yeah, since functions are also Objects (and in-fact first class variables in Javascript), even functions have methods which are... well, functions themselves.
All functions inherit from the global Function, and two of its many methods are call and apply, and both can be used to manipulate the value of this in the function on which they are called.
function foo () { console.log (this, arguments); }
var thisArg = {myObj: "is cool"};
foo.call(thisArg, 1, 2, 3);
This is a typical example of using call. It basically takes the first parameter and sets this in the function foo as a reference to thisArg. All other parameters passed to call is passed to the function foo as arguments.
So the above code will log {myObj: "is cool"}, [1, 2, 3] in the console. Pretty nice way to change the value of this in any function.
apply is almost the same as call accept that it takes only two parameters: thisArg and an array which contains the arguments to be passed to the function. So the above call call can be translated to apply like this:
foo.apply(thisArg, [1,2,3])
Note that call and apply can override the value of this set by dot method invocation we discussed in the second bullet.
Simple enough :)
Presenting.... bind!
bind is a brother of call and apply. It is also a method inherited by all functions from the global Function constructor in Javascript. The difference between bind and call/apply is that both call and apply will actually invoke the function. bind, on the other hand, returns a new function with the thisArg and arguments pre-set. Let's take an example to better understand this:
function foo (a, b) {
console.log (this, arguments);
}
var thisArg = {myObj: "even more cool now"};
var bound = foo.bind(thisArg, 1, 2);
console.log (typeof bound); // logs `function`
console.log (bound);
/* logs `function () { native code }` */
bound(); // calling the function returned by `.bind`
// logs `{myObj: "even more cool now"}, [1, 2]`
See the difference between the three? It is subtle, but they are used differently. Like call and apply, bind will also over-ride the value of this set by dot-method invocation.
Also note that neither of these three functions do any change to the original function. call and apply would return the value from freshly constructed functions while bind will return the freshly constructed function itself, ready to be called.
Extra stuff, copy this
Sometimes, you don't like the fact that this changes with scope, especially nested scope. Take a look at the following example.
var myObj = {
hello: function () {
return "world"
},
myMethod: function () {
// copy this, variable names are case-sensitive
var that = this;
// callbacks ftw \o/
foo.bar("args", function () {
// I want to call `hello` here
this.hello(); // error
// but `this` references to `foo` damn!
// oh wait we have a backup \o/
that.hello(); // "world"
});
}
};
In the above code, we see that the value of this changed with the nested scope, but we wanted the value of this from the original scope. So we 'copied' this to that and used the copy instead of this. Clever, eh?
Index:
What is held in this by default?
What if we call the function as a method with Object-dot notation?
What if we use the new keyword?
How do we manipulate this with call and apply?
Using bind.
Copying this to solve nested-scope issues.
"this" is all about scope. Every function has its own scope, and since everything in JS is an object, even a function can store some values into itself using "this". OOP 101 teaches that "this" is only applicable to instances of an object. Therefore, every-time a function executes, a new "instance" of that function has a new meaning of "this".
Most people get confused when they try to use "this" inside of anonymous closure functions like:
(function(value) {
this.value = value;
$('.some-elements').each(function(elt){
elt.innerHTML = this.value; // uh oh!! possibly undefined
});
})(2);
So here, inside each(), "this" doesn't hold the "value" that you expect it to (from this.value = value; above it). So, to get over this (no pun intended) problem, a developer could:
(function(value) {
var self = this; // small change
self.value = value;
$('.some-elements').each(function(elt){
elt.innerHTML = self.value; // phew!! == 2
});
})(2);
Try it out; you'll begin to like this pattern of programming
Since this thread has bumped up, I have compiled few points for readers new to this topic.
How is the value of this determined?
We use this similar to the way we use pronouns in natural languages like English: “John is running fast because he is trying to catch the train.” Instead we could have written “… John is trying to catch the train”.
var person = {
firstName: "Penelope",
lastName: "Barrymore",
fullName: function () {
// We use "this" just as in the sentence above:
console.log(this.firstName + " " + this.lastName);
// We could have also written:
console.log(person.firstName + " " + person.lastName);
}
}
this is not assigned a value until an object invokes the function where it is defined. In the global scope, all global variables and functions are defined on the window object. Therefore, this in a global function refers to (and has the value of) the global window object.
When use strict, this in global and in anonymous functions that are not bound to any object holds a value of undefined.
The this keyword is most misunderstood when: 1) we borrow a method that uses this, 2) we assign a method that uses this to a variable, 3) a function that uses this is passed as a callback function, and 4) this is used inside a closure — an inner function. (2)
What holds the future
Defined in ECMA Script 6, arrow-functions adopt the this binding from the
enclosing (function or global) scope.
function foo() {
// return an arrow function
return (a) => {
// `this` here is lexically inherited from `foo()`
console.log(this.a);
};
}
var obj1 = { a: 2 };
var obj2 = { a: 3 };
var bar = foo.call(obj1);
bar.call( obj2 ); // 2, not 3!
While arrow-functions provide an alternative to using bind(), it’s important to note that they essentially are disabling the traditional this mechanism in favor of more widely understood lexical scoping. (1)
References:
this & Object Prototypes, by Kyle Simpson. © 2014 Getify Solutions.
javascriptissexy.com - http://goo.gl/pvl0GX
Angus Croll - http://goo.gl/Z2RacU
this in JavaScript always refers to the 'owner' of the function that is being executed.
If no explicit owner is defined, then the top most owner, the window object, is referenced.
So if I did
function someKindOfFunction() {
this.style = 'foo';
}
element.onclick = someKindOfFunction;
this would refer to the element object. But be careful, a lot of people make this mistake.
<element onclick="someKindOfFunction()">
In the latter case, you merely reference the function, not hand it over to the element. Therefore, this will refer to the window object.
Every execution context in javascript has a this parameter that is set by:
How the function is called (including as an object method, use of call and apply, use of new)
Use of bind
Lexically for arrow functions (they adopt the this of their outer execution context)
Whether the code is in strict or non-strict mode
Whether the code was invoked using eval
You can set the value of this using func.call, func.apply or func.bind.
By default, and what confuses most beginners, when a listener is called after an event is raised on a DOM element, the this value of the function is the DOM element.
jQuery makes this trivial to change with jQuery.proxy.
Daniel, awesome explanation! A couple of words on this and good list of this execution context pointer in case of event handlers.
In two words, this in JavaScript points the object from whom (or from whose execution context) the current function was run and it's always read-only, you can't set it anyway (such an attempt will end up with 'Invalid left-hand side in assignment' message.
For event handlers: inline event handlers, such as <element onclick="foo">, override any other handlers attached earlier and before, so be careful and it's better to stay off of inline event delegation at all.
And thanks to Zara Alaverdyan who inspired me to this list of examples through a dissenting debate :)
el.onclick = foo; // in the foo - obj
el.onclick = function () {this.style.color = '#fff';} // obj
el.onclick = function() {doSomething();} // In the doSomething -
Window
el.addEventListener('click',foo,false) // in the foo - obj
el.attachEvent('onclick, function () { // this }') // window, all the
compliance to IE :)
<button onclick="this.style.color = '#fff';"> // obj
<button onclick="foo"> // In the foo - window, but you can <button
onclick="foo(this)">
Here is one good source of this in JavaScript.
Here is the summary:
global this
In a browser, at the global scope, this is the windowobject
<script type="text/javascript">
console.log(this === window); // true
var foo = "bar";
console.log(this.foo); // "bar"
console.log(window.foo); // "bar"
In node using the repl, this is the top namespace. You can refer to it as global.
>this
{ ArrayBuffer: [Function: ArrayBuffer],
Int8Array: { [Function: Int8Array] BYTES_PER_ELEMENT: 1 },
Uint8Array: { [Function: Uint8Array] BYTES_PER_ELEMENT: 1 },
...
>global === this
true
In node executing from a script, this at the global scope starts as an empty object. It is not the same as global
\\test.js
console.log(this); \\ {}
console.log(this === global); \\ fasle
function this
Except in the case of DOM event handlers or when a thisArg is provided (see further down), both in node and in a browser using this in a function that is not called with new references the global scope…
<script type="text/javascript">
foo = "bar";
function testThis() {
this.foo = "foo";
}
console.log(this.foo); //logs "bar"
testThis();
console.log(this.foo); //logs "foo"
</script>
If you use use strict;, in which case this will be undefined
<script type="text/javascript">
foo = "bar";
function testThis() {
"use strict";
this.foo = "foo";
}
console.log(this.foo); //logs "bar"
testThis(); //Uncaught TypeError: Cannot set property 'foo' of undefined
</script>
If you call a function with new the this will be a new context, it will not reference the global this.
<script type="text/javascript">
foo = "bar";
function testThis() {
this.foo = "foo";
}
console.log(this.foo); //logs "bar"
new testThis();
console.log(this.foo); //logs "bar"
console.log(new testThis().foo); //logs "foo"
</script>
prototype this
Functions you create become function objects. They automatically get a special prototype property, which is something you can assign values to. When you create an instance by calling your function with new you get access to the values you assigned to the prototype property. You access those values using this.
function Thing() {
console.log(this.foo);
}
Thing.prototype.foo = "bar";
var thing = new Thing(); //logs "bar"
console.log(thing.foo); //logs "bar"
It is usually a mistake to assign arrays or objects on the prototype. If you want instances to each have their own arrays, create them in the function, not the prototype.
function Thing() {
this.things = [];
}
var thing1 = new Thing();
var thing2 = new Thing();
thing1.things.push("foo");
console.log(thing1.things); //logs ["foo"]
console.log(thing2.things); //logs []
object this
You can use this in any function on an object to refer to other properties on that object. This is not the same as an instance created with new.
var obj = {
foo: "bar",
logFoo: function () {
console.log(this.foo);
}
};
obj.logFoo(); //logs "bar"
DOM event this
In an HTML DOM event handler, this is always a reference to the DOM element the event was attached to
function Listener() {
document.getElementById("foo").addEventListener("click",
this.handleClick);
}
Listener.prototype.handleClick = function (event) {
console.log(this); //logs "<div id="foo"></div>"
}
var listener = new Listener();
document.getElementById("foo").click();
Unless you bind the context
function Listener() {
document.getElementById("foo").addEventListener("click",
this.handleClick.bind(this));
}
Listener.prototype.handleClick = function (event) {
console.log(this); //logs Listener {handleClick: function}
}
var listener = new Listener();
document.getElementById("foo").click();
HTML this
Inside HTML attributes in which you can put JavaScript, this is a reference to the element.
<div id="foo" onclick="console.log(this);"></div>
<script type="text/javascript">
document.getElementById("foo").click(); //logs <div id="foo"...
</script>
eval this
You can use eval to access this.
function Thing () {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
eval("console.log(this.foo)"); //logs "bar"
}
var thing = new Thing();
thing.logFoo();
with this
You can use with to add this to the current scope to read and write to values on this without referring to this explicitly.
function Thing () {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
with (this) {
console.log(foo);
foo = "foo";
}
}
var thing = new Thing();
thing.logFoo(); // logs "bar"
console.log(thing.foo); // logs "foo"
jQuery this
the jQuery will in many places have this refer to a DOM element.
<div class="foo bar1"></div>
<div class="foo bar2"></div>
<script type="text/javascript">
$(".foo").each(function () {
console.log(this); //logs <div class="foo...
});
$(".foo").on("click", function () {
console.log(this); //logs <div class="foo...
});
$(".foo").each(function () {
this.click();
});
</script>
There is a lot of confusion regarding how "this" keyword is interpreted in JavaScript. Hopefully this article will lay all those to rest once and for all. And a lot more. Please read the entire article carefully. Be forewarned that this article is long.
Irrespective of the context in which it is used, "this" always references the "current object" in Javascript. However, what the "current object" is differs according to context. The context may be exactly 1 of the 6 following:
Global (i.e. Outside all functions)
Inside Direct "Non Bound Function" Call (i.e. a function that has not been bound by calling functionName.bind)
Inside Indirect "Non Bound Function" Call through functionName.call and functionName.apply
Inside "Bound Function" Call (i.e. a function that has been bound by calling functionName.bind)
While Object Creation through "new"
Inside Inline DOM event handler
The following describes each of this contexts one by one:
Global Context (i.e. Outside all functions):
Outside all functions (i.e. in global context) the "current
object" (and hence the value of "this") is always the
"window" object for browsers.
Inside Direct "Non Bound Function" Call:
Inside a Direct "Non Bound Function" Call, the object that
invoked the function call becomes the "current object" (and hence
the value of "this"). If a function is called without a explicit current object, the current object is either the "window" object (For Non Strict Mode) or undefined (For Strict Mode) . Any function (or variable) defined in
Global Context automatically becomes a property of the "window" object.For e.g Suppose function is defined in Global Context as
function UserDefinedFunction(){
alert(this)
}
it becomes the property of the window object, as if you have defined
it as
window.UserDefinedFunction=function(){
alert(this)
}
In "Non Strict Mode", Calling/Invoking this function directly through "UserDefinedFunction()" will automatically call/invoke
it as "window.UserDefinedFunction()" making "window" as the
"current object" (and hence the value of "this") within "UserDefinedFunction".Invoking this function in "Non Strict Mode" will result in the following
UserDefinedFunction() // displays [object Window] as it automatically gets invoked as window.UserDefinedFunction()
In "Strict Mode", Calling/Invoking the function directly through
"UserDefinedFunction()" will "NOT" automatically call/invoke it as "window.UserDefinedFunction()".Hence the "current
object" (and the value of "this") within
"UserDefinedFunction" shall be undefined. Invoking this function in "Strict Mode" will result in the following
UserDefinedFunction() // displays undefined
However, invoking it explicitly using window object shall result in
the following
window.UserDefinedFunction() // "always displays [object Window] irrespective of mode."
Let us look at another example. Please look at the following code
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction
}
var o2={
c:3,
d:4,
f:UserDefinedFunction
}
o1.f() // Shall display 1,2,undefined,undefined
o2.f() // Shall display undefined,undefined,3,4
In the above example we see that when "UserDefinedFunction" was
invoked through o1, "this" takes value of o1 and the
value of its properties "a" and "b" get displayed. The value
of "c" and "d" were shown as undefined as o1 does
not define these properties
Similarly when "UserDefinedFunction" was invoked through o2,
"this" takes value of o2 and the value of its properties "c" and "d" get displayed.The value of "a" and "b" were shown as undefined as o2 does not define these properties.
Inside Indirect "Non Bound Function" Call through functionName.call and functionName.apply:
When a "Non Bound Function" is called through
functionName.call or functionName.apply, the "current object" (and hence the value of "this") is set to the value of
"this" parameter (first parameter) passed to call/apply. The following code demonstrates the same.
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction
}
var o2={
c:3,
d:4,
f:UserDefinedFunction
}
UserDefinedFunction.call(o1) // Shall display 1,2,undefined,undefined
UserDefinedFunction.apply(o1) // Shall display 1,2,undefined,undefined
UserDefinedFunction.call(o2) // Shall display undefined,undefined,3,4
UserDefinedFunction.apply(o2) // Shall display undefined,undefined,3,4
o1.f.call(o2) // Shall display undefined,undefined,3,4
o1.f.apply(o2) // Shall display undefined,undefined,3,4
o2.f.call(o1) // Shall display 1,2,undefined,undefined
o2.f.apply(o1) // Shall display 1,2,undefined,undefined
The above code clearly shows that the "this" value for any "NON
Bound Function" can be altered through call/apply. Also,if the
"this" parameter is not explicitly passed to call/apply, "current object" (and hence the value of "this") is set to "window" in Non strict mode and "undefined" in strict mode.
Inside "Bound Function" Call (i.e. a function that has been bound by calling functionName.bind):
A bound function is a function whose "this" value has been
fixed. The following code demonstrated how "this" works in case
of bound function
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction,
bf:null
}
var o2={
c:3,
d:4,
f:UserDefinedFunction,
bf:null
}
var bound1=UserDefinedFunction.bind(o1); // permanantly fixes "this" value of function "bound1" to Object o1
bound1() // Shall display 1,2,undefined,undefined
var bound2=UserDefinedFunction.bind(o2); // permanantly fixes "this" value of function "bound2" to Object o2
bound2() // Shall display undefined,undefined,3,4
var bound3=o1.f.bind(o2); // permanantly fixes "this" value of function "bound3" to Object o2
bound3() // Shall display undefined,undefined,3,4
var bound4=o2.f.bind(o1); // permanantly fixes "this" value of function "bound4" to Object o1
bound4() // Shall display 1,2,undefined,undefined
o1.bf=UserDefinedFunction.bind(o2) // permanantly fixes "this" value of function "o1.bf" to Object o2
o1.bf() // Shall display undefined,undefined,3,4
o2.bf=UserDefinedFunction.bind(o1) // permanantly fixes "this" value of function "o2.bf" to Object o1
o2.bf() // Shall display 1,2,undefined,undefined
bound1.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
bound1.apply(o2) // Shall still display 1,2,undefined,undefined. "apply" cannot alter the value of "this" for bound function
o2.bf.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
o2.bf.apply(o2) // Shall still display 1,2,undefined,undefined."apply" cannot alter the value of "this" for bound function
As given in the code above, "this" value for any "Bound Function"
CANNOT be altered through call/apply. Also, if the "this"
parameter is not explicitly passed to bind, "current object"
(and hence the value of "this" ) is set to "window" in Non
strict mode and "undefined" in strict mode. One more thing.
Binding an already bound function does not change the value of "this".
It remains set as the value set by first bind function.
While Object Creation through "new":
Inside a constructor function, the "current object" (and hence the value of
"this") references the object that is currently being created
through "new" irrespective of the bind status of the function. However
if the constructor is a bound function it shall get called with
predefined set of arguments as set for the bound function.
Inside Inline DOM event handler:
Please look at the following HTML Snippet
<button onclick='this.style.color=white'>Hello World</button>
<div style='width:100px;height:100px;' onclick='OnDivClick(event,this)'>Hello World</div>
The "this" in above examples refer to "button" element and the
"div" element respectively.
In the first example, the font color of the button shall be set to
white when it is clicked.
In the second example when the "div" element is clicked it shall
call the OnDivClick function with its second parameter
referencing the clicked div element. However the value of "this"
within OnDivClick SHALL NOT reference the clicked div
element. It shall be set as the "window object" or
"undefined" in Non strict and Strict Modes respectively (if OnDivClick is an unbound function) or set to a predefined
Bound value (if OnDivClick is a bound function)
The following summarizes the entire article
In Global Context "this" always refers to the "window" object
Whenever a function is invoked, it is invoked in context of an
object ("current object"). If the current object is not explicitly provided,
the current object is the "window object" in NON Strict
Mode and "undefined" in Strict Mode by default.
The value of "this" within a Non Bound function is the reference to object in context of which the function is invoked ("current object")
The value of "this" within a Non Bound function can be overriden by
call and apply methods of the function.
The value of "this" is fixed for a Bound function and cannot be
overriden by call and apply methods of the function.
Binding and already bound function does not change the value of "this". It remains set as the value set by first bind function.
The value of "this" within a constructor is the object that is being
created and initialized
The value of "this" within an inline DOM event handler is reference
to the element for which the event handler is given.
Probably the most detailed and comprehensive article on this is the following:
Gentle explanation of 'this' keyword in JavaScript
The idea behind this is to understand that the function invocation types have the significant importance on setting this value.
When having troubles identifying this, do not ask yourself:
Where is this taken from?
but do ask yourself:
How is the function invoked?
For an arrow function (special case of context transparency) ask yourself:
What value has this where the arrow function is defined?
This mindset is correct when dealing with this and will save you from headache.
This is the best explanation I've seen: Understand JavaScripts this with Clarity
The this reference ALWAYS refers to (and holds the value of) an
object—a singular object—and it is usually used inside a function or a
method, although it can be used outside a function in the global
scope. Note that when we use strict mode, this holds the value of
undefined in global functions and in anonymous functions that are not
bound to any object.
There are Four Scenarios where this can be confusing:
When we pass a method (that uses this) as an argument to be used as a callback function.
When we use an inner function (a closure). It is important to take note that closures cannot access the outer function’s this variable by using the this keyword because the this variable is accessible only by the function itself, not by inner functions.
When a method which relies on this is assigned to a variable across contexts, in which case this references another object than originally intended.
When using this along with the bind, apply, and call methods.
He gives code examples, explanations, and solutions, which I thought was very helpful.
this is one of the misunderstood concept in JavaScript because it behaves little differently from place to place. Simply, this refers to the "owner" of the function we are currently executing.
this helps to get the current object (a.k.a. execution context) we work with. If you understand in which object the current function is getting executed, you can understand easily what current this is
var val = "window.val"
var obj = {
val: "obj.val",
innerMethod: function () {
var val = "obj.val.inner",
func = function () {
var self = this;
return self.val;
};
return func;
},
outerMethod: function(){
return this.val;
}
};
//This actually gets executed inside window object
console.log(obj.innerMethod()()); //returns window.val
//Breakdown in to 2 lines explains this in detail
var _inn = obj.innerMethod();
console.log(_inn()); //returns window.val
console.log(obj.outerMethod()); //returns obj.val
Above we create 3 variables with same name 'val'. One in global context, one inside obj and the other inside innerMethod of obj. JavaScript resolves identifiers within a particular context by going up the scope chain from local go global.
Few places where this can be differentiated
Calling a method of a object
var status = 1;
var helper = {
status : 2,
getStatus: function () {
return this.status;
}
};
var theStatus1 = helper.getStatus(); //line1
console.log(theStatus1); //2
var theStatus2 = helper.getStatus;
console.log(theStatus2()); //1
When line1 is executed, JavaScript establishes an execution context (EC) for the function call, setting this to the object referenced by whatever came before the last ".". so in the last line you can understand that a() was executed in the global context which is the window.
With Constructor
this can be used to refer to the object being created
function Person(name){
this.personName = name;
this.sayHello = function(){
return "Hello " + this.personName;
}
}
var person1 = new Person('Scott');
console.log(person1.sayHello()); //Hello Scott
var person2 = new Person('Hugh');
var sayHelloP2 = person2.sayHello;
console.log(sayHelloP2()); //Hello undefined
When new Person() is executed, a completely new object is created. Person is called and its this is set to reference that new object.
Function call
function testFunc() {
this.name = "Name";
this.myCustomAttribute = "Custom Attribute";
return this;
}
var whatIsThis = testFunc();
console.log(whatIsThis); //window
var whatIsThis2 = new testFunc();
console.log(whatIsThis2); //testFunc() / object
console.log(window.myCustomAttribute); //Custom Attribute
If we miss new keyword, whatIsThis referes to the most global context it can find(window)
With event handlers
If the event handler is inline, this refers to global object
<script type="application/javascript">
function click_handler() {
alert(this); // alerts the window object
}
</script>
<button id='thebutton' onclick='click_handler()'>Click me!</button>
When adding event handler through JavaScript, this refers to DOM element that generated the event.
You can also manipulate the context using .apply() .call() and .bind()
JQuery proxy is another way you can use to make sure this in a function will be the value you desire. (Check Understanding $.proxy(), jQuery.proxy() usage)
What does var that = this means in JavaScript
The value of "this" depends on the "context" in which the function is executed. The context can be any object or the global object, i.e., window.
So the Semantic of "this" is different from the traditional OOP languages. And it causes problems:
1. when a function is passed to another variable (most likely, a callback); and 2. when a closure is invoked from a member method of a class.
In both cases, this is set to window.
In pseudoclassical terms, the way many lectures teach the 'this' keyword is as an object instantiated by a class or object constructor. Each time a new object is constructed from a class, imagine that under the hood a local instance of a 'this' object is created and returned. I remember it taught like this:
function Car(make, model, year) {
var this = {}; // under the hood, so to speak
this.make = make;
this.model = model;
this.year = year;
return this; // under the hood
}
var mycar = new Car('Eagle', 'Talon TSi', 1993);
// ========= under the hood
var this = {};
this.make = 'Eagle';
this.model = 'Talon TSi';
this.year = 1993;
return this;
Whould this help? (Most confusion of 'this' in javascript is coming from the fact that it generally is not linked to your object, but to the current executing scope -- that might not be exactly how it works but is always feels like that to me -- see the article for a complete explanation)
A little bit info about this keyword
Let's log this keyword to the console in global scope without any more code but
console.log(this)
In Client/Browser this keyword is a global object which is window
console.log(this === window) // true
and
In Server/Node/Javascript runtime this keyword is also a global object which is module.exports
console.log(this === module.exports) // true
console.log(this === exports) // true
Keep in mind exports is just a reference to module.exports
I have a different take on this from the other answers that I hope is helpful.
One way to look at JavaScript is to see that there are only 1 way to call a function1. It is
functionObject.call(objectForThis, arg0, arg1, arg2, ...);
There is always some value supplied for objectForThis.
Everything else is syntactic sugar for functionObject.call
So, everything else can be described by how it translates into functionObject.call.
If you just call a function then this is the "global object" which in the browser is the window
function foo() {
console.log(this);
}
foo(); // this is the window object
In other words,
foo();
was effectively translated into
foo.call(window);
Note that if you use strict mode then this will be undefined
'use strict';
function foo() {
console.log(this);
}
foo(); // this is the window object
which means
In other words,
foo();
was effectively translated into
foo.call(undefined);
In JavaScript there are operators like + and - and *. There is also the dot operator which is .
The . operator when used with a function on the right and an object on the left effectively means "pass object as this to function.
Example
const bar = {
name: 'bar',
foo() {
console.log(this);
},
};
bar.foo(); // this is bar
In other words bar.foo() translates into const temp = bar.foo; temp.call(bar);
Note that it doesn't matter how the function was created (mostly...). All of these will produce the same results
const bar = {
name: 'bar',
fn1() { console.log(this); },
fn2: function() { console.log(this); },
fn3: otherFunction,
};
function otherFunction() { console.log(this) };
bar.fn1(); // this is bar
bar.fn2(); // this is bar
bar.fn3(); // this is bar
Again these all are just syntactic sugar for
{ const temp = bar.fn1; temp.call(bar); }
{ const temp = bar.fn2; temp.call(bar); }
{ const temp = bar.fn3; temp.call(bar); }
One other wrinkle is the prototype chain. When you use a.b JavaScript first looks on the object referenced directly by a for the property b. If b is not found on the object then JavaScript will look in the object's prototype to find b.
There are various ways to define an object's prototype, the most common in 2019 is the class keyword. For the purposes of this though it doesn't matter. What matters is that as it looks in object a for property b if it finds property b on the object or in it's prototype chain if b ends up being a function then the same rules as above apply. The function b references will be called using the call method and passing a as objectForThis as shown a the top of this answer.
Now. Let's imagine we make a function that explicitly sets this before calling another function and then call it with the . (dot) operator
function foo() {
console.log(this);
}
function bar() {
const objectForThis = {name: 'moo'}
foo.call(objectForThis); // explicitly passing objectForThis
}
const obj = {
bar,
};
obj.bar();
Following the translation to use call, obj.bar() becomes const temp = obj.bar; temp.call(obj);. When we enter the bar function we call foo but we explicitly passed in another object for objectForThis so when we arrive at foo this is that inner object.
This is what both bind and => functions effectively do. They are more syntactic sugar. They effectively build a new invisible function exactly like bar above that explicitly sets this before it calls whatever function is specified. In the case of bind this is set to whatever you pass to bind.
function foo() {
console.log(this);
}
const bar = foo.bind({name: 'moo'});
// bind created a new invisible function that calls foo with the bound object.
bar();
// the objectForThis we are passing to bar here is ignored because
// the invisible function that bind created will call foo with with
// the object we bound above
bar.call({name: 'other'});
Note that if functionObject.bind did not exist we could make our own like this
function bind(fn, objectForThis) {
return function(...args) {
return fn.call(objectForthis, ...args);
};
}
and then we could call it like this
function foo() {
console.log(this);
}
const bar = bind(foo, {name:'abc'});
Arrow functions, the => operator are syntactic sugar for bind
const a = () => {console.log(this)};
is the same as
const tempFn = function() {console.log(this)};
const a = tempFn.bind(this);
Just like bind, a new invisible function is created that calls the given function with a bound value for objectForThis but unlike bind the object to be bound is implicit. It's whatever this happens to be when the => operator is used.
So, just like the rules above
const a = () => { console.log(this); } // this is the global object
'use strict';
const a = () => { console.log(this); } // this is undefined
function foo() {
return () => { console.log(this); }
}
const obj = {
foo,
};
const b = obj.foo();
b();
obj.foo() translates to const temp = obj.foo; temp.call(obj); which means the arrow operator inside foo will bind obj to a new invisible function and return that new invisible function which is assigned to b. b() will work as it always has as b.call(window) or b.call(undefined) calling the new invisible function that foo created. That invisible function ignores the this passed into it and passes obj as objectForThis` to the arrow function.
The code above translates to
function foo() {
function tempFn() {
console.log(this);
}
return tempFn.bind(this);
}
const obj = {
foo,
};
const b = obj.foo();
b.call(window or undefined if strict mode);
1apply is another function similar to call
functionName.apply(objectForThis, arrayOfArgs);
But as of ES6 conceptually you can even translate that into
functionName.call(objectForThis, ...arrayOfArgs);
"this" in JavaScript
this is one of the properties of the Execution Context.
this property is created every time a function is executed and not
before that.
Its value is not static but rather depends on how it is being used.
takes a value that points to the owner of the function in which it is
used
There are different ways in which the "this" keyword can be used, below are the example for it (method, regular function, arrow function, Event listener, Explicit function Binding).
1. Inside a method.
this === (to the object that is calling the Method).
In the above example the method " fullName()" is called by an Object "person" hence the value of this inside the method " fullName()" will be equal to the "person" Object.
2. Inside a Function.
i) function declaration/expression
in loose mode this === window (object)
in Strict mode this === undefined
Note : this property works the same while defining a function using function declaration or function expression approach.
ii) Arrow Function :
Arrow Function does not have their own this property, they take the value of this as their surrounding Function.
If the surrounding function is not present i.e if they are defined at the global level then this === window (object)
3. Event Listener
this === object on which the handler is attached.
click event bind to the Document object
In the above example since the click handler is attached to the "document" object, this will be equal to the "document" object
4. Explicit Function Binding (call, Apply, Bind)
The call() and apply() methods are predefined JavaScript methods.
They can both be used to call an object method with another object as an argument.
In the above example this inside the "printFullDetails()" is explicitly set to the personObj1 and personObj2 by passing as the first argument to call method.
You can Explore more about call, apply and bind methods here.
this use for Scope just like this
<script type="text/javascript" language="javascript">
$('#tbleName tbody tr').each(function{
var txt='';
txt += $(this).find("td").eq(0).text();
\\same as above but synatx different
var txt1='';
txt1+=$('#tbleName tbody tr').eq(0).text();
alert(txt1)
});
</script>
value of txt1 and txt is same
in Above example
$(this)=$('#tbleName tbody tr') is Same
Summary this Javascript:
The value of this is determined by how the function is invoked not, where it was created!
Usually the value of this is determined by the Object which is left of the dot. (window in global space)
In event listeners the value of this refers to the DOM element on which the event was called.
When in function is called with the new keyword the value of this refers to the newly created object
You can manipulate the value of this with the functions: call, apply, bind
Example:
let object = {
prop1: function () {console.log(this);}
}
object.prop1(); // object is left of the dot, thus this is object
const myFunction = object.prop1 // We store the function in the variable myFunction
myFunction(); // Here we are in the global space
// myFunction is a property on the global object
// Therefore it logs the window object
Example event listeners:
document.querySelector('.foo').addEventListener('click', function () {
console.log(this); // This refers to the DOM element the eventListener was invoked from
})
document.querySelector('.foo').addEventListener('click', () => {
console.log(this); // Tip, es6 arrow function don't have their own binding to the this v
}) // Therefore this will log the global object
.foo:hover {
color: red;
cursor: pointer;
}
<div class="foo">click me</div>
Example constructor:
function Person (name) {
this.name = name;
}
const me = new Person('Willem');
// When using the new keyword the this in the constructor function will refer to the newly created object
console.log(me.name);
// Therefore, the name property was placed on the object created with new keyword.
To understand "this" properly one must understand the context and scope and difference between them.
Scope: In javascript scope is related to the visibility of the variables, scope achieves through the use of the function. (Read more about scope)
Context: Context is related to objects. It refers to the object to which a function belongs. When you use the JavaScript “this” keyword, it refers to the object to which function belongs. For example, inside of a function, when you say: “this.accoutNumber”, you are referring to the property “accoutNumber”, that belongs to the object to which that function belongs.
If the object “myObj” has a method called “getMyName”, when the JavaScript keyword “this” is used inside of “getMyName”, it refers to “myObj”. If the function “getMyName” were executed in the global scope, then “this” refers to the window object (except in strict mode).
Now let's see some example:
<script>
console.log('What is this: '+this);
console.log(this);
</script>
Runnig abobve code in browser output will:
According to the output you are inside of the context of the window object, it is also visible that window prototype refers to the Object.
Now let's try inside of a function:
<script>
function myFunc(){
console.log('What is this: '+this);
console.log(this);
}
myFunc();
</script>
Output:
The output is the same because we logged 'this' variable in the global scope and we logged it in functional scope, we didn't change the context. In both case context was same, related to widow object.
Now let's create our own object. In javascript, you can create an object in many ways.
<script>
var firstName = "Nora";
var lastName = "Zaman";
var myObj = {
firstName:"Lord",
lastName:'Baron',
printNameGetContext:function(){
console.log(firstName + " "+lastName);
console.log(this.firstName +" "+this.lastName);
return this;
}
}
var context = myObj.printNameGetContext();
console.log(context);
</script>
Output:
So from the above example, we found that 'this' keyword is referring to a new context that is related to myObj, and myObject also has prototype chain to Object.
Let's go throw another example:
<body>
<button class="btn">Click Me</button>
<script>
function printMe(){
//Terminal2: this function declared inside window context so this function belongs to the window object.
console.log(this);
}
document.querySelector('.btn').addEventListener('click', function(){
//Terminal1: button context, this callback function belongs to DOM element
console.log(this);
printMe();
})
</script>
</body>
output:
Make sense right? (read comments)
If you having trouble to understand the above example let's try with our own callback;
<script>
var myObj = {
firstName:"Lord",
lastName:'Baron',
printName:function(callback1, callback2){
//Attaching callback1 with this myObj context
this.callback1 = callback1;
this.callback1(this.firstName +" "+this.lastName)
//We did not attached callback2 with myObj so, it's reamin with window context by default
callback2();
/*
//test bellow codes
this.callback2 = callback2;
this.callback2();
*/
}
}
var callback2 = function (){
console.log(this);
}
myObj.printName(function(data){
console.log(data);
console.log(this);
}, callback2);
</script>
output:
Now let's Understand Scope, Self, IIFE and THIS how behaves
var color = 'red'; // property of window
var obj = {
color:'blue', // property of window
printColor: function(){ // property of obj, attached with obj
var self = this;
console.log('In printColor -- this.color: '+this.color);
console.log('In printColor -- self.color: '+self.color);
(function(){ // decleard inside of printColor but not property of object, it will executed on window context.
console.log(this)
console.log('In IIFE -- this.color: '+this.color);
console.log('In IIFE -- self.color: '+self.color);
})();
function nestedFunc(){// decleard inside of printColor but not property of object, it will executed on window context.
console.log('nested fun -- this.color: '+this.color);
console.log('nested fun -- self.color: '+self.color);
}
nestedFunc(); // executed on window context
return nestedFunc;
}
};
obj.printColor()(); // returned function executed on window context
</script>
Output is pretty awesome right?

Get an object's name as the value of this

I am trying to understand the value of this at different points in a script. Questions similar to mine have been answered in this forum but those answers are considerably above my current learning level.
In my code experiments, I am using console.logs to return the this value. The value returned is always as expected, but the format of the returned value is inconsistent, which leads me to wonder why.
This code returns the expected Window object for the first 3 log commands to be executed but returns only the object literal for the 4th command, executed from the object's method.
var myName = {
name: "James",
sayName: function() {
console.log(this, 4);
console.log(this.name)
}
}
console.log(this, 1);
function myFunction() {
console.log(this, 2);
function nestFunction() {
console.log(this, 3);
myName.sayName();
}
nestFunction();
}
myFunction();
I have 3 questions: Why doesn't console.log return the name of the object? Is there a way to make it do so? Is there a simple way to do that other than console.log? Any help would be appreciated.
Ok I was going through your code to see what you specifically mean
here is the short explanation as to why THIS is different in some of the places
This keyword refers to the object it belongs to. Generally you used it to refer to the global window object .That's what is reflecting in your console log 1,2,3 .
Calling this in static javaScript object will return the javaScript object ,not the window object that is what is reflecting in the console.log(this,4).
So it gives you a way to call elements inside a static object .
Another way to understand this keyword is to look at constructors .The best example of the keyword
this
is inside a constructor function
var myObj = function(){
function myObj(ref)
{
this.name = "";
this.Item = "";
this.ref = ref;
this.speak();
}
myObj.prototype.speak =function()
{
this.name = 'James';
this.item = 'cheese';
console.log(this.ref)
//and the constuctor object
console.log(this)
}
return myObj;
}();
var e = new myObj('a Refrence string');
This should give you a basic understanding of how this works
here is more info to get you started Wschools.com

function in rootscope, can't access rootscope variable

In my app.run I have an function which get some text from an global variable from an other file. In that variable there are some keywords with an language attribute, which allows me to only get the requested text and filter out the right language.
I made an function for that but I can't get access the $rootScope.language variable in that function which I need for getting the right text.
function getTourTranslation(key){
console.log("getTourTranslation", key);
var lang = $rootScope.language;
var step = _.get(steps, key);
return step[lang]
}
So language is undefined, and so $rootScope.language is, but the variable exists and contains the right language key for the current language on the site. How can I get the content of that variabele without passing the language as variable into the function?
I also tried as $rootScope.getTourTranslation = function(key) but no luck
edit:
This is how the language variable is filled. We use angular-translate, so that is the $translate service. This code is placed above the getTourTranslation function.
$rootScope.changeLanguage = function (langKey) {
if(langKey){
if(langKey.length == 2) {
$translate.use(langKey.toLowerCase()+"_"+langKey.toUpperCase());
$rootScope.language = langKey;
} else if(langKey.length == 5) {
$translate.use(langKey);
$rootScope.language = langKey.substring(0,2);
}
}
};
$rootScope.$on('$translateChangeSuccess', function () {
if($translate.use()){
$rootScope.language = $translate.use().substring(0,2);
if($state.$current && !$state.$current.self.abstract) {
$state.reload();
}
}
});
$rootScope.changeLanguage($translate.use());
It is not possible that variable defined on $rootScope is not available withing the same context.
I can imagine only one case:
it calls getTourTranslation so early so none of changeLanguage or $translateChangeSuccess handler ran
The problem was, that $rootScope.language was called before it was initialized.
So, I placed the call to the getTourTranslation() function in an function which is called after firing an button. So, the right variables are now only initialized when they are needed instead of always.
So, I fixed two things, and that all based on the comment from #BotanMan

Angular self invoking function [duplicate]

I would like to know what this means:
(function () {
})();
Is this basically saying document.onload?
It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.
It has nothing to do with any event-handler for any events (such as document.onload).
Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.
This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:
(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)
Correction suggested by Guffa:
The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.
Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :
((foo) => {
// do something with foo here foo
})('foo value')
It's just an anonymous function that is executed right after it's created.
It's just as if you assigned it to a variable, and used it right after, only without the variable:
var f = function () {
};
f();
In jQuery there is a similar construct that you might be thinking of:
$(function(){
});
That is the short form of binding the ready event:
$(document).ready(function(){
});
But the above two constructs are not IIFEs.
An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.
Three more common wordings:
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
If there are no special requirements for its return value, then we can write:
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
Alternatively, it can be:
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
You can even write:
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
That construct is called an Immediately Invoked Function Expression (IIFE) which means it gets executed immediately. Think of it as a function getting called automatically when the interpreter reaches that function.
Most Common Use-case:
One of its most common use cases is to limit the scope of a variable made via var. Variables created via var have a scope limited to a function so this construct (which is a function wrapper around certain code) will make sure that your variable scope doesn't leak out of that function.
In following example, count will not be available outside the immediately invoked function i.e. the scope of count will not leak out of the function. You should get a ReferenceError, should you try to access it outside of the immediately invoked function anyway.
(function () {
var count = 10;
})();
console.log(count); // Reference Error: count is not defined
ES6 Alternative (Recommended)
In ES6, we now can have variables created via let and const. Both of them are block-scoped (unlike var which is function-scoped).
Therefore, instead of using that complex construct of IIFE for the use case I mentioned above, you can now write much simpler code to make sure that a variable's scope does not leak out of your desired block.
{
let count = 10;
}
console.log(count); // ReferenceError: count is not defined
In this example, we used let to define count variable which makes count limited to the block of code, we created with the curly brackets {...}.
I call it a “Curly Jail”.
It declares an anonymous function, then calls it:
(function (local_arg) {
// anonymous function
console.log(local_arg);
})(arg);
That is saying execute immediately.
so if I do:
var val = (function(){
var a = 0; // in the scope of this function
return function(x){
a += x;
return a;
};
})();
alert(val(10)); //10
alert(val(11)); //21
Fiddle: http://jsfiddle.net/maniator/LqvpQ/
Second Example:
var val = (function(){
return 13 + 5;
})();
alert(val); //18
(function () {
})();
This is called IIFE (Immediately Invoked Function Expression). One of the famous JavaScript design patterns, it is the heart and soul of the modern day Module pattern. As the name suggests it executes immediately after it is created. This pattern creates an isolated or private scope of execution.
JavaScript prior to ECMAScript 6 used lexical scoping, so IIFE was used for simulating block scoping. (With ECMAScript 6 block scoping is possible with the introduction of the let and const keywords.)
Reference for issue with lexical scoping
Simulate block scoping with IIFE
The performance benefit of using IIFE’s is the ability to pass commonly used global objects like window, document, etc. as an argument by reducing the scope lookup. (Remember JavaScript looks for properties in local scope and way up the chain until global scope). So accessing global objects in local scope reduces the lookup time like below.
(function (globalObj) {
//Access the globalObj
})(window);
This is an Immediately Invoked Function Expression in Javascript:
To understand IIFE in JS, lets break it down:
Expression: Something that returns a value
Example: Try out following in chrome console. These are expressions in JS.
a = 10
output = 10
(1+3)
output = 4
Function Expression:
Example:
// Function Expression
var greet = function(name){
return 'Namaste' + ' ' + name;
}
greet('Santosh');
How function expression works:
- When JS engine runs for the first time (Execution Context - Create Phase), this function (on the right side of = above) does not get executed or stored in the memory. Variable 'greet' is assigned 'undefined' value by the JS engine.
- During execution (Execution Context - Execute phase), the funtion object is created on the fly (its not executed yet), gets assigned to 'greet' variable and it can be invoked using 'greet('somename')'.
3. Immediately Invoked Funtion Expression:
Example:
// IIFE
var greeting = function(name) {
return 'Namaste' + ' ' + name;
}('Santosh')
console.log(greeting) // Namaste Santosh.
How IIFE works:
- Notice the '()' immediately after the function declaration. Every funtion object has a 'CODE' property attached to it which is callable. And we can call it (or invoke it) using '()' braces.
- So here, during the execution (Execution Context - Execute Phase), the function object is created and its executed at the same time
- So now, the greeting variable, instead of having the funtion object, has its return value ( a string )
Typical usecase of IIFE in JS:
The following IIFE pattern is quite commonly used.
// IIFE
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
we are doing two things over here.
a) Wrapping our function expression inside braces (). This goes to tell the syntax parser the whatever placed inside the () is an expression (function expression in this case) and is a valid code.
b) We are invoking this funtion at the same time using the () at the end of it.
So this function gets created and executed at the same time (IIFE).
Important usecase for IIFE:
IIFE keeps our code safe.
- IIFE, being a function, has its own execution context, meaning all the variables created inside it are local to this function and are not shared with the global execution context.
Suppose I've another JS file (test1.js) used in my applicaiton along with iife.js (see below).
// test1.js
var greeting = 'Hello';
// iife.js
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
console.log(greeting) // No collision happens here. It prints 'Hello'.
So IIFE helps us to write safe code where we are not colliding with the global objects unintentionally.
No, this construct just creates a scope for naming. If you break it in parts you can see that you have an external
(...)();
That is a function invocation. Inside the parenthesis you have:
function() {}
That is an anonymous function. Everything that is declared with var inside the construct will be visible only inside the same construct and will not pollute the global namespace.
That is a self-invoking anonymous function.
Check out the W3Schools explanation of a self-invoking function.
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without
being called.
Function expressions will execute automatically if the expression is
followed by ().
You cannot self-invoke a function declaration.
This is the self-invoking anonymous function. It is executed while it is defined. Which means this function is defined and invokes itself immediate after the definition.
And the explanation of the syntax is: The function within the first () parenthesis is the function which has no name and by the next (); parenthesis you can understand that it is called at the time it is defined. And you can pass any argument in this second () parenthesis which will be grabbed in the function which is in the first parenthesis. See this example:
(function(obj){
// Do something with this obj
})(object);
Here the 'object' you are passing will be accessible within the function by 'obj', as you are grabbing it in the function signature.
Start here:
var b = 'bee';
console.log(b); // global
Put it in a function and it is no longer global -- your primary goal.
function a() {
var b = 'bee';
console.log(b);
}
a();
console.log(b); // ReferenceError: b is not defined -- *as desired*
Call the function immediately -- oops:
function a() {
var b = 'bee';
console.log(b);
}(); // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'
Use the parentheses to avoid a syntax error:
(function a() {
var b = 'bee';
console.log(b);
})(); // OK now
You can leave off the function name:
(function () { // no name required
var b = 'bee';
console.log(b);
})();
It doesn't need to be any more complicated than that.
Self-executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The code
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
2
1
By using this syntax you avoid colliding with global variables declared elsewhere in your JavaScript code.
It is a function expression, it stands for Immediately Invoked Function Expression (IIFE). IIFE is simply a function that is executed right after it is created. So insted of the function having to wait until it is called to be executed, IIFE is executed immediately. Let's construct the IIFE by example. Suppose we have an add function which takes two integers as args and returns the sum
lets make the add function into an IIFE,
Step 1: Define the function
function add (a, b){
return a+b;
}
add(5,5);
Step2: Call the function by wrap the entire functtion declaration into parentheses
(function add (a, b){
return a+b;
})
//add(5,5);
Step 3: To invock the function immediatly just remove the 'add' text from the call.
(function add (a, b){
return a+b;
})(5,5);
The main reason to use an IFFE is to preserve a private scope within your function. Inside your javascript code you want to make sure that, you are not overriding any global variable. Sometimes you may accidentaly define a variable that overrides a global variable. Let's try by example. suppose we have an html file called iffe.html and codes inside body tag are-
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Well, above code will execute with out any question, now assume you decleard a variable named document accidentaly or intentional.
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
const document = "hi there";
console.log(document);
</script>
</body>
you will endup in a SyntaxError: redeclaration of non-configurable global property document.
But if your desire is to declear a variable name documet you can do it by using IFFE.
<body>
<div id = 'demo'></div>
<script>
(function(){
const document = "hi there";
this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
console.log(document);
})();
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Output:
Let's try by an another example, suppose we have an calculator object like bellow-
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
</script>
</body>
Well it's working like a charm, what if we accidently re-assigne the value of calculator object.
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
calculator = "scientific calculator";
console.log(calculator.mul(5,5));
</script>
</body>
yes you will endup with a TypeError: calculator.mul is not a function iffe.html
But with the help of IFFE we can create a private scope where we can create another variable name calculator and use it;
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
var cal = (function(){
var calculator = {
sub:function(a,b){
return a-b;
},
div:function(a,b){
return a/b;
}
}
console.log(this.calculator.mul(5,10));
console.log(calculator.sub(10,5));
return calculator;
})();
console.log(calculator.add(5,10));
console.log(cal.div(10,5));
</script>
</body>
Output:
TL;DR: Expressions can be enclosed in parenthesis, which would conflict with function calling if the expression and block forms of function were combined.
I like counter-examples because they paint a great picture of the logic, and noone else listed any. You might ask, "Why can't the browser see function(){}() and just assume its an expression?" Let's juxtapose the issue with three examples.
var x;
// Here, fibonacci is a block function
function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
}
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
Observe how things change when we turn the function into an expression.
var x;
// Here, fibonacci is a function expression
(function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
})
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
The same thing happens when you use the not-operator instead of parenthesis because both operators turn the statement into an expression:
var x;
// Here, fibonacci is a function expression
! function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
}
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
By turning the function into an expression, it gets executed by the (x = 9) two lines down from it. Thanks to separate behaviors for expression functions and block functions, both examples run fine without ambiguity (specs-wise).
Name Scoping
Another important observation is that named block functions are visible to the entire scope, whereas function expressions are only visible to themselves. In other words, fibonacci is only visible to the last console.log when it is a block in the first example. In all three examples, fibonacci is visible to itself, allowing fibonacci to call itself, which is recursion.
Arrow Functions
Another aspect to the logic is arrow functions. The specs would have had to include arbitrary rules and exceptions for arrow functions if the definitions of block and expression functions were merged together:
function hello() {console.log("Hello World")}
(x) => console.log("hello " + x)
console.log("If you are reading this, no errors occurred");
Although function blocks work fine, function expressions followed by an arrow function produce a syntax error:
! function hello() {console.log("Hello World")}
(x) => console.log("hello " + x)
console.log("If you are reading this, no errors occurred");
Here, it is ambiguous whether the (x) on line two is calling the function on the preceding line or whether it is the function arguments for an arrow function.
Note that arrow functions have been indeed to the ECMAScript standard over the years and were not a factor in the initial design of the language; my point is that a differentiation between expression and block functions helps JavaScript syntax to be a little more logical and coherent.
Self-executing anonymous function. It's executed as soon as it is created.
One short and dummy example where this is useful is:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
So instead of creating a list each time, you create it only once (less overhead).
It is called IIFE - Immediately Invoked Function Expression. Here is an example to show it's syntax and usage. It is used to scope the use of variables only till the function and not beyond.
(function () {
function Question(q,a,c) {
this.q = q;
this.a = a;
this.c = c;
}
Question.prototype.displayQuestion = function() {
console.log(this.q);
for (var i = 0; i < this.a.length; i++) {
console.log(i+": "+this.a[i]);
}
}
Question.prototype.checkAnswer = function(ans) {
if (ans===this.c) {
console.log("correct");
} else {
console.log("incorrect");
}
}
var q1 = new Question('Is Javascript the coolest?', ['yes', 'no'], 0);
var q2 = new Question('Is python better than Javascript?', ['yes', 'no', 'both are same'], 2);
var q3 = new Question('Is Javascript the worst?', ['yes', 'no'], 1);
var questions = [q1, q2, q3];
var n = Math.floor(Math.random() * questions.length)
var answer = parseInt(prompt(questions[n].displayQuestion()));
questions[n].checkAnswer(answer);
})();
Already many good answers here but here are my 2 cents :p
You can use IIFE (Immediately Invoked Function Expression) for:
Avoiding pollution in the global namespace.
Variables defined in IIFE (or even any normal function) don't overwrite definitions in global scope.
Protecting code from being accessed by outer code.
Everything that you define within the IIFE can be only be accessed within the IIFE. It protects code from being modified by outer code. Only what you explicitly return as the result of function or set as value to outer variables is accessible by outer code.
Avoid naming functions that you don't need to use repeatedly.
Though it's possible to use a named function in IIFE pattern you don't do it as there is no need to call it repeatedly, generally.
For Universal Module Definitions which is used in many JS libraries. Check this question for details.
IIFE is generally used in following fashion :
(function(param){
//code here
})(args);
You can omit the parentheses () around anonymous function and use void operator before anonymous function.
void function(param){
//code here
}(args);
IIFE (Immediately invoked function expression) is a function which executes as soon as the script loads and goes away.
Consider the function below written in a file named iife.js
(function(){
console.log("Hello Stackoverflow!");
})();
This code above will execute as soon as you load iife.js and will print 'Hello Stackoverflow!' on the developer tools' console.
For a Detailed explanation see Immediately-Invoked Function Expression (IIFE)
One more use case is memoization where a cache object is not global:
var calculate = (function() {
var cache = {};
return function(a) {
if (cache[a]) {
return cache[a];
} else {
// Calculate heavy operation
cache[a] = heavyOperation(a);
return cache[a];
}
}
})();
The following code:
(function () {
})();
is called an immediately invoked function expression (IIFE).
It is called a function expression because the ( yourcode ) operator in Javascript force it into an expression. The difference between a function expression and a function declaration is the following:
// declaration:
function declaredFunction () {}
// expressions:
// storing function into variable
const expressedFunction = function () {}
// Using () operator, which transforms the function into an expression
(function () {})
An expression is simply a bunch of code which can be evaluated to a single value. In case of the expressions in the above example this value was a single function object.
After we have an expression which evaluates to a function object we then can immediately invoke the function object with the () operator. For example:
(function() {
const foo = 10; // all variables inside here are scoped to the function block
console.log(foo);
})();
console.log(foo); // referenceError foo is scoped to the IIFE
Why is this useful?
When we are dealing with a large code base and/or when we are importing various libraries the chance of naming conflicts increases. When we are writing certain parts of our code which is related (and thus is using the same variables) inside an IIFE all of the variables and function names are scoped to the function brackets of the IIFE. This reduces chances of naming conflicts and lets you name them more careless (e.g. you don't have to prefix them).
The reason self-evoking anonymous functions are used is they should never be called by other code since they "set up" the code which IS meant to be called (along with giving scope to functions and variables).
In other words, they are like programs that "make classes', at the beginning of program. After they are instantiated (automatically), the only functions that are available are the ones returned in by the anonymous function. However, all the other 'hidden' functions are still there, along with any state (variables set during scope creation).
Very cool.
In ES6 syntax (posting for myself, as I keep landing on this page looking for a quick example):
// simple
const simpleNumber = (() => {
return true ? 1 : 2
})()
// with param
const isPositiveNumber = ((number) => {
return number > 0 ? true : false
})(4)
This function is called self-invoking function. A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked(Called) immediately after its definition. Read more here
What these functions do is that when the function is defined, The function is immediately called, which saves time and extra lines of code(as compared to calling it on a seperate line).
Here is an example:
(function() {
var x = 5 + 4;
console.log(x);
})();
An immediately invoked function expression (IIFE) is a function that's executed as soon as it's created. It has no connection with any events or asynchronous execution. You can define an IIFE as shown below:
(function() {
// all your code here
// ...
})();
The first pair of parentheses function(){...} converts the code inside the parentheses into an expression.The second pair of parentheses calls the function resulting from the expression.
An IIFE can also be described as a self-invoking anonymous function. Its most common usage is to limit the scope of a variable made via var or to encapsulate context to avoid name collisions.
This is a more in depth explanation of why you would use this:
"The primary reason to use an IIFE is to obtain data privacy. Because JavaScript's var scopes variables to their containing function, any variables declared within the IIFE cannot be accessed by the outside world."
http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-expressions.html
Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.
Two ways we can create IIFE
(function () {
"use strict";
var app = angular.module("myModule", []);
}());
OR
(function () {
"use strict";
var app = angular.module("myModule", []);
})();
In the code snippet above, “var app” is a local variable now.
Usually, we don't invoke a function immediately after we write it in the program.
In extremely simple terms, when you call a function right after its creation, it is called IIFE - a fancy name.

Resources