Skip to content

Instantly share code, notes, and snippets.

@liang799
Last active January 6, 2022 13:34
Show Gist options
  • Save liang799/d67cb8d67ba6606a13178ca80449c67a to your computer and use it in GitHub Desktop.
Save liang799/d67cb8d67ba6606a13178ca80449c67a to your computer and use it in GitHub Desktop.
Javascript this Notes

this

this is confusing, so I condesed what I have learned from MDN and Yehuda's Blog into a cheatsheet

Simple functions

function hello(thing) {
  console.log("Hello " + thing);
}

// this:
hello("world")

// desugars to:
hello.call(window, "world");

But for strict mode, it will not refer to the global object window

Member functions

var person = {
  name: "Brendan Eich",
  hello: function(thing) {
    console.log(this + " says hello " + thing);
  }
}

// this:
person.hello("world")

// desugars to this:
person.hello.call(person, "world");

Notice that for member function, this becomes the object person, instead of the global object window

Bind

function hello(thing) {
  console.log(this + " says hello " + thing);
}

person = { name: "Brendan Eich" }
person.hello = hello;

person.hello("world") // still desugars to person.hello.call(person, "world")

hello("world") // "[object DOMWindow]world"

Notice how this is not persistent and can yield surprising results. Thus, bind solves the problem by binding this to a specific object.

Summary

Global Context

Global object, window

Function Context

Global object, window, if not in strict mode

Class Context

A regular object

Bind

To avoid confusion and let this be presistent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment