</> Code Corner

JavaScript · JS Functions & Objects · Lesson 41

JS this Keyword

What this refers to in different contexts.

In JavaScript, this refers to an object. Which object depends on how this is being invoked.

Context this refers to
In an object method The object
Alone The global object
In a function (strict mode) undefined
In an event handler The element that received the event
With call(), apply(), bind() Any object you choose
In an arrow function The this of the surrounding code

Example

<p id="demo"></p>
<script>
const person = {
  firstName: "John",
  fullName: function () { return this.firstName + " Doe"; }
};
const member = { firstName: "Hege" };
const bound = person.fullName.bind(member);
document.getElementById("demo").innerHTML =
  person.fullName() + "<br>" + person.fullName.call(member) + "<br>" + bound();
</script>

Keep reading “JS this Keyword”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋