Skip to content

Instantly share code, notes, and snippets.

@neuodev
Last active January 1, 2023 13:32
Show Gist options
  • Save neuodev/fe06bd78d017ac68740c62f0ea3f7d3e to your computer and use it in GitHub Desktop.
Save neuodev/fe06bd78d017ac68740c62f0ea3f7d3e to your computer and use it in GitHub Desktop.

What is this?

This cheet sheat is made by Ahmed Ibrahim ❤️

This Keyword

This cheet sheat summaries the key points from my YouTube video about the this keyword

Introduction

  • this doesn't have a specific value. It dpens on where, who, how it is called!

  • this is different in strict mode and non strict mode

  • in non-strict, this always ref. to an object

  • in strict mode, this can have any value

Basic example

const test = {
  prop: 42,
  func: function () {
    return this.prop;
  },
};

console.log(test.func()); // 42

Contexts

Function Context

Regular Functions

  • this value depends on how the function is called and the function type(reg., arrow, callback, constructor)

  • this value depends the object that the function is accessed on. notice how the function is the same but the value is different

    function getThis() {
      return this;
    }
    
    const obj1 = { name: "obj1", getThis };
    const obj2 = { name: "obj2", getThis };
    
    console.log(obj1.getThis()); // obj1
    console.log(obj2.getThis()); // obj2
  • this depends on the caller not which object it defined at

    const obj4 = {
      name: "obj4",
      getThis() {
        return this;
      },
    };
    
    const obj5 = { name: "obj5", getThis: obj4.getThis() };
    
    console.log(obj5.getThis()); // obj5
  • Function in strict mode: this will have any value(number, undefined, string,...object,...) not just objects

    function getThisStrict() {
      "use strict";
      return this;
    }
    
    Number.prototype.getThisStrict = getThisStrict;
    console.log(typeof (1).getThisStrict()); // "number"
    
    console.log(getThisStrict()); // "undefined"
  • Function in non-strict-mode: this will can't be any thing other than object

    function getThis() {
      return this;
    }
    
    Number.prototype.getThis = getThis;
    console.log(typeof (1).getThis()); // "object"
    console.log(getThis() === globalThis); // true
  • Control the value of this You can use call or bind or apply

    function getThis() {
      return this;
    }
    
    const obj1 = { name: "ojb1", getThis };
    
    console.log(ob1.getThis());
    console.log(getThis()); // Window or Global this
    console.log(getThis.call({ name: "new object" })); // new object

Callbacks

Learn more about function callbacks

Value of this depends on the caller of the function

function logThis() {
  "use strict";
  console.log(this);
}

[1, 2, 3].forEach(logThis); // 3x'undefined'
setTimeout(logThis, 1000); // Window or globalObject

Arrow Function

Learn more about arrow functions

It creates a closure

const obj = {
  name: "obj1",
  func: () => this, // Window :)
  func2() {
    return () => this;
  },
};

obj.func(); // window
obj.func2()(); // obj1
obj.func2.bind({ name: "obj2" })()(); // obj2
obj.func2().call({ name: "obj2" })(); // obj1

Function constructors

Read more about function constructors

The new keyword will create an empty object and will point this toward it. This means that this === object(new).

function Car() {
  this.speed = 20;
}

// new => {} <- this
let car = new Car();
console.log(car.speed);

Expect when the constructor return a value

function Car() {
  // Will not work as `Car` returned something
  this.speed = 20;
  return {
    speed: 30,
  };
}

let car = new Car();
console.log(car.speed); // 30!!

Class

Read more about classes

  • Value of this depends on static vs instance property
class Car {
  // On the `instance` of the class
  a = this;
  // On the class (Car) itslef
  static b = this;
}

const toyota = new Car();
console.log(toyota.a === toyota); // true
console.log(Car.b === Car); // true

Global Context

Outside of any function or class. Might be inside blocks or arrow functions.

This will be equal to the Window object.

console.log(this === window); // true
this.b = "Jone";
console.log(window.b); // Jone
console.log(b); // Jone

Example of global and local context

const obj = { a: "Local" };

var a = "Window";

// Note: non-strict
function getA() {
  return this.a;
}

getA(); // "Window"
getA.call(obj); // "Local"

DOM

In this case this points to the e.currentTarget.

function clickHandler(e) {
  console.log("CurrentTarget", e.currentTarget);
  console.log("This", this);
  console.log("Target", e.target);

  console.log("this === e.currentTarget =>", this === e.currentTarget);
  console.log("this === e.target =>", this === e.target);
}

document.getElementById("container").addEventListener("click", clickHandler);

"Inline" event handler

In this case this points to the "current element" Note: that this only applys for the global this!

<button onclick="alert(this.tagName.toLowerCase());">Show this</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment