This Keyword in Javascript
Make JavaScript powerful using this keyword
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 the global context
When you use this
in the global context, it is bound to the global object (window
in browser)
document.write(this); //[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 immediately 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
3. Function context
Inside a function, the value of this
depends on how the function is called.
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]
Since the following code is not in strict mode, and because the value of this
is not set by the call, this
will default to the global object, which is window
in a browser.
In strict mode, however, if the value of this
is not set when entering an execution context, it remains as undefined
, as shown in the following example:
function f1() {
return this;
}// In a browser:
f1() === window; // true// In Node:
f1() === globalThis; // truefunction f2() {
'use strict'; // see strict mode
return this;
}f2() === undefined; // true
4.Class context
When using this inside of methods of an ES6 class, it always points to the current object.
class Dog {
constructor (food) {
document.write(this); // [object Object]
this.food=food;
} eat() {
document.write('Hi! My food is' + this.food);
}
}var Tuffy= new Dog('chicken');
Tuffy.eat(); // Hi! My food is chicken
5. When used inside the 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. In this case, the new operator calls the internal [[Construct]] method of the A
the function which, in turn, after object creation, calls the internal [[Call]] method, all the same function A
, having provided as this
value newly created objects.
function A()
{
console.log(this); // newly created object
this.x = 10;
}
var a = new A();
console.log(a.x); // 10
6.When used inside a function defined on the 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 o = {f: function() { return this.a + this.b; }};
var p = Object.create(o);
p.a = 1;
p.b = 4;console.log(p.f()); // 5
In this example, the object assigned to the variable p
doesn't have its own f
the property, it inherits it from its prototype. But it doesn't matter that the lookup for f
eventually finds a member with that name on o
; the lookup began as a reference to p.f
, so this
inside the function takes the value of the object referred to as p
. That is, since f
is called as a method of p
, its this
refers to p
. This is an interesting feature of JavaScript's prototype inheritance.
7.This inside event handlers
When a function is used as an event handler, its this
is set to the element on which the listener is placed.
When the code is called from an inline handler, its this
is set to the DOM element on which the listener is placed:
<button onclick="alert(this.tagName.toLowerCase());">
Show this
</button>//button
In the case below, the inner function’s this
isn't set so it returns the global/window object.
<button onclick="alert((function() { return this; })());">
Show inner this
</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
.
const globalArrowFunction = () => {
return this;
};console.log(globalArrowFunction()); //windowconst obj= {
method1: () => {return this},
method2: function(){
return () => {return this};
}
};console.log(obj.method1()); //windowconst contextLessFunction = obj.method1;console.log(contextLessFunction()); //windowconsole.log(obj.method2()()) //objconst innerArrowFunction = obj.method2();console.log(innerArrowFunction()); //obj