Who is ‘this’…?

Julia Zhou
3 min readSep 9, 2020

Understanding ‘this’ keyword in JavaScript

“The object that is executing the current function.”

The ‘this’ keyword is a tricky concept to grasp in JavaScript. By definition it refers to the object it belongs to depending on where it is which makes it easier to understand through examples.

When ‘this’ is a global object

  • Without context, the below console.log function would return the global object which is Window object when accessing in a browser

Want to read this story later? Save it in Journal.

  • Below, ‘this’ is being called within a function but again refers to the Window object since the function is being executed from the global object just as the example above.
  • Within an object method, when ‘this’ is used within an arrow function, it also returns the global object. In the example below the object is returned as ‘undefined’. To correct this, regular function syntax should be used instead. (See following example.)

When ‘this’ is an owner object

  • Below within the person object with the method of phrase(), the ‘this’ refers to the object in which it is called. The console.log functions returns the entire object and the template string.
  • Below within the person object with the method of phrase() uses regular function syntax. However, when ‘this’ is called within the forEach method, the entire function will find to the global object — to mitigate this, ‘this’ can be passed in as an argument within the forEach method to recognize the owner object.

When using ‘this’ in a constructor function

  • Below the petOwner function takes in an argument of name and then it assigns this.name to the argument. To initialize the constructor function, we created a constant newPetOwner where we created a new petOwner object with the name that we passed in.

Further Reading:

📝 Save this story in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--