Course

this Keyword

In this lesson, you'll learn about the keyword in JavaScript, which is a fundamental concept for understanding how functions and objects interact in different contexts.

Introduction

The keyword in JavaScript refers to the object that is executing the current function. It provides a way to access the properties and methods of the object within which the function is being executed. Understanding is crucial for working with object-oriented programming in JavaScript.

Using it in a Function

Let's explore how works with a simple example:

JAVASCRIPT

1function Sentence(words) {
2  this.words = words;
3  console.log(this);
4}
5
6const S = new Sentence("hello there, we are learning about the `this` keyword");

Explanation

  1. Function Definition: We define a function that takes an input parameter .
  2. Assigning Properties: Inside the function, we assign to the input parameter . This means that the property of the object being created will hold the value passed to the function.
  3. Logging : We use to print the current context of . When the function is called with the keyword, refers to the new object being created.
  4. Creating an Instance: We create a new instance of by calling . This creates a new object, and within the function refers to this new object.

What Happens When You Run the Code

  • When you run the code, the function is executed in the context of a new object. The keyword inside the function refers to this new object.
  • The statement outputs the new object, showing its properties, including which is set to the string "hello there, we are learning about the keyword".

Key Points to Remember

  • Context Matters: The value of depends on how a function is called. In the context of a constructor function (like ), refers to the new object being created.
  • Global Context: If a function is called without an object context (e.g., not as a method or constructor), refers to the global object (or in strict mode).
  • Method Context: When a function is called as a method of an object, refers to the object the method is called on.

Understanding the keyword is essential for working with objects and functions in JavaScript, as it allows you to access and manipulate the properties of the object within which a function is executed.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Intervals and Timers