Getting Started with JavaScript: Understanding the ‘this’ Keyword

Posted by

JavaScript for Beginners – The ‘this’ keyword

JavaScript for Beginners – The ‘this’ keyword

If you’re just starting out with JavaScript, you may have come across the ‘this’ keyword and wondered what it is and how to use it. In this article, we’ll explore the basics of the ‘this’ keyword in JavaScript.

What is the ‘this’ keyword?

In JavaScript, the ‘this’ keyword refers to the object that is executing the current function. It is a special keyword that is used within methods to refer to the object that the method is being called on.

How to use the ‘this’ keyword

When a function is called as a method of an object, the value of ‘this’ is set to the object that is calling the method. For example:

  
var person = {
  name: 'John',
  greet: function() {
    console.log('Hello, my name is ' + this.name);
  }
};

person.greet(); // Output: Hello, my name is John
  

In this example, when the greet method is called on the person object, the value of ‘this’ inside the method is set to the person object, so ‘this.name’ refers to the name property of the person object.

Using ‘this’ in constructor functions

The ‘this’ keyword is commonly used in constructor functions to refer to the newly created object. When a new object is created using the ‘new’ keyword, ‘this’ is set to the new object inside the constructor function. For example:

  
function Person(name, age) {
  this.name = name;
  this.age = age;
}

var john = new Person('John', 30);
console.log(john.name); // Output: John
console.log(john.age); // Output: 30
  

In this example, when the Person constructor function is called with the ‘new’ keyword, ‘this’ is set to the newly created object (john), so ‘this.name’ and ‘this.age’ refer to the properties of the new object.

Conclusion

The ‘this’ keyword is a powerful tool in JavaScript that allows you to access the current object within a method or constructor function. Understanding how ‘this’ works is essential for building complex and dynamic applications with JavaScript.