The Concept of `this` in JavaScript

Ahmad Awais ⚡️
3 min readJan 18, 2018
The Concept of this in JavaScript!

TL;DR

  1. If a function is called with the new keyword, this will be the resulting object.
  2. If a function is called with .call(), .apply() or .bind(), this will be the object that is passed in.
  3. If a function is called on an object, obj.foo(), this will be the object it was called on.
  4. If a function is called on its own, sayMyName(), this will be either undefined (if in use strict; mode) or the global object (if in non-strict mode).

Concept #1

If a function is called with the new keyword, this will be the resulting object.


let myName = new String('Ahmad Awais');
typeOf(myName); // object <=== this is the resulting object.

Concept #2

If a function is called with .call(), .apply() or .bind(), this will be the object that is passed in.

let person = {
name: "Ahmad Awais"
};
let sayMyName = function() {
console.log(this.name);
};
sayMyName.call(person); //<== this = obj 'person' that is passed in.

Concept #3

If a function is called on an object, obj.foo(), this will be the object it was called on.

let person = {
name: "Ahmad Awais",
sayMyName: function() {
console.log(this.name);
}
};
person.sayMyName(); //<== this = obj 'person' on which the functions was called

Concept #4

If a function is called on its own, sayMyName(), this will be either undefined (if in use strict; mode) or the global object (if in non-strict mode).

"use strict";let name = "Ahmad Awais";let sayMyName = function() {
console.log(this.name);
};
sayMyName(); // undefined <== this is undefined.

ES6 TIP:

An arrow function expression has a shorter syntax than a function expression and does not have its own this.

Thank you, Kyle Simpson for his incredible work on You Don’t Know JS and the good folks at Icons8.

The Concept of `this` in JavaScript
🔰 Learn the concept of `this` in JavaScript! — [five simple concepts]. A FOSS (Free & Open Source Software) project developed by Ahmad Awais.

— Follow Ahmad’s #FOSS work on GitHub @AhmadAwais

— Say 👋 on Twitter @MrAhmadAwais

Hello, we’re the WordPress Couple!

I (Ahmad Awais) am a Full Stack Web Developer and a regular core contributor at WordPress. My significant other (Maedah Batool) is a Technical Project Manager, and she’s also a WordPress Core Contributor. Together with our team, we run the WPCouple.com.

If you’d like to get insights into our love for open source software, professional full stack development, WordPress community, the growth of JavaScript or growing a family, building, and bootstrapping a business, then subscribe to our premium newsletter called ↣ The WordPress Takeaway! 🔥

--

--

Ahmad Awais ⚡️

Award-winning DevRel Eng. ❯ NodeCLI.comVSCode.pro ❯ Google Developers Expert ❯ Node.js Community Committee ❯ WordPress Core ❯ Self-confessed tech comedian!