DEV Community

Cover image for A quick intro to 'this' in JavaScript
Natalie Smith 🏳️‍🌈
Natalie Smith 🏳️‍🌈

Posted on

A quick intro to 'this' in JavaScript

Probably one of the most confusing aspects of JavaScript is finding out what 'this' means. In this post, I will try to go over the basics of the 'this' keyword when used in a method, function, and by itself.

this in a method

A method is a property on an object that is a function. For example:

const greeting = {
  someProp: "🦄", 
  sayHello: function () {
    return "Hello 👋"
  }
}

console.log(greeting.sayHello()) // Hello 👋

sayHello is our method. Another frequently used method is console.log()

When using the 'this' keyword in a method it will be referencing the object owner.

var first = "Jane"
var last = "Fonda"

const person = {
  first: "Sally",
  last: "Sweet",
  fullName: function () {
    return this.first + " " + this.last
  }
}

console.log(person.fullName()) // Sally Sweet

The object owner, in this case, is person so it will be referencing the person object. Even though we have the same variable names out there in the global scope, when using the 'this' keyword in a method it will be referencing properties on the object owner.

this in a function

If you using the this keyword in a function then it will be referencing the window (if you're in the browser)

var lucky = 13; // note: let and const will not work 

function add (num) {
  return this.lucky + num;
}

console.log(add(10)) // 23 
    function sum(a, b) {
      console.log(this === window) // true
      this.favNum = 13 // sets 13 in the global obj
      return this.favNum + a + b
    }

    window.favNum // 13
    console.log(sum(10, 10)) // 33

this alone

If you paste in the following, the 'this' keyword will be referencing the global scope which in this case is the window object in the browser.

console.log(this)
console.log(this === window) // true

Conclusion

There is still a lot more to cover for 'this' and by no means does this post go over all the possibilities. It does try to open up the basics and hopefully this was able to help clarify some things about 'this'

Thank you for reading and if I missed something in this post please comment down below, I'm not an expert so feedback is always appreciated.

cover image from https://i.ytimg.com/vi/gvicrj31JOM/maxresdefault.jpg

Top comments (0)