snippetjavascriptTip
Understanding the "this" keyword in JavaScript
Viewed 0 times
keywordjavascriptunderstandingthisthe
Problem
In JavaScript, the
this keyword refers to the object that is currently executing the code. The short version of what this evaluates to is as follows:- By default,
thisrefers to the global object. - In a function, when not in strict mode,
thisrefers to the global object. - In a function, when in strict mode,
thisisundefined. - In an arrow function,
thisretains the value of the enclosing lexical context'sthis.
Solution
console.log(this === window); // true- In a function, when not in strict mode,
thisrefers to the global object. - In a function, when in strict mode,
thisisundefined. - In an arrow function,
thisretains the value of the enclosing lexical context'sthis. - In an object method,
thisrefers to the object the method was called on. - In a constructor call,
thisis bound to the new object being constructed. - In an event handler,
thisis bound to the element on which the listener is placed.
Code Snippets
console.log(this === window); // truefunction f() {
return this;
}
console.log(f() === window); // true'use strict';
function f() {
return this;
}
console.log(f()); // undefinedContext
From 30-seconds-of-code: this
Revisions (0)
No revisions yet.