this Identifier

Another very commonly misunderstood concept in JavaScript is the this identifier. Again, there’s a couple of chapters on it in the this & Object Prototypes title of this series, so here we’ll just briefly introduce the concept.

While it may often seem that this is related to “object-oriented patterns,” in JS this is a different mechanism.

If a function has a this reference inside it, that this reference usually points to an object. But which object it points to depends on how the function was called.

It’s important to realize that this does not refer to the function itself, as is the most common misconception.

Here’s a quick illustration:

  1. function foo() {
  2. console.log( this.bar );
  3. }
  4. var bar = "global";
  5. var obj1 = {
  6. bar: "obj1",
  7. foo: foo
  8. };
  9. var obj2 = {
  10. bar: "obj2"
  11. };
  12. // --------
  13. foo(); // "global"
  14. obj1.foo(); // "obj1"
  15. foo.call( obj2 ); // "obj2"
  16. new foo(); // undefined

There are four rules for how this gets set, and they’re shown in those last four lines of that snippet.

  1. foo() ends up setting this to the global object in non-strict mode — in strict mode, this would be undefined and you’d get an error in accessing the bar property — so "global" is the value found for this.bar.
  2. obj1.foo() sets this to the obj1 object.
  3. foo.call(obj2) sets this to the obj2 object.
  4. new foo() sets this to a brand new empty object.

Bottom line: to understand what this points to, you have to examine how the function in question was called. It will be one of those four ways just shown, and that will then answer what this is.

Note: For more information about this, see Chapters 1 and 2 of the this & Object Prototypes title of this series.