Skip to content

Instantly share code, notes, and snippets.

@ksdev-pl
Last active August 29, 2015 14:12
Show Gist options
  • Save ksdev-pl/e4ec0fc2478a065ffad3 to your computer and use it in GitHub Desktop.
Save ksdev-pl/e4ec0fc2478a065ffad3 to your computer and use it in GitHub Desktop.
"This" in JavaScript #js
  1. The keyword "this" refers to whatever is left of the dot at call-time.
  2. If there's nothing to the left of the dot, then "this" is the root scope (e.g. Window).
  3. A few functions change the behavior of "this"—bind, call and apply
  4. The keyword "new" binds this to the object just created

So if you're using the value of "this" in someFunction...

thing.someFunction(); // this === thing
someFunction();       // this === Window
new someFunction();   // this === the newly created object

There are three ways to invoke a function. The meaning of this depends on which method was used:

  • If a function is invoked in the form foo.func(), then the value of this is foo.
  • If a function is invoked in the form func() (sometimes called "bare"), then the value of this is the "root object". In browsers the root object is window, in Node this it's the global object [0]. It's easier to make a bare invocation than you think:
var bareFunc = foo.func;
bareFunc();
  • If a function is invoked via the call() or apply() function, then the value of this is whatever the invocation specifies. For example, in func.call(foo) the value of this will be foo.

If you ever pass a function to something else as a callback, you have no guarantee what the value of this will be when it is called. For example, if you register a callback for a click event, the value of this is whatever the caller wants it to be (in this case, it'll be the DOM element that's emitting the event):

function MyFoo(elem) {
  elem.addEventListener('click', this.onClick);
}

MyFoo.prototype.onClick = function(e) {
  // `this` is whatever the caller wanted it to be
}

You can force this to be a specific value by using the bind() function:

function MyFoo(elem) {
  elem.addEventListener('click', this.onClick.bind(this));
}

MyFoo.prototype.onClick = function(e) {
  // `this` has been bound to what you think it should be.
}

[0] However, if you're in strict mode, then in either case this will be undefined.

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