PART 1. Misconceptions of “This”

The keyword this is an identifier for values (similar to a variable or function parameter), this is designed to support object-oriented programming. Rather than assigning values explicitly in your code, you assume this gets bound to “the right object” automatically. Nevertheless, you have as much control in your code over the binding for this as you do over the bindings for function parameters. Also, you can’t always rely on the interpreter to bind this to the object that seems like it should be the “most focal.”

COPYRIGHT © 2018 CodeStates

This behaves almost exactly like a parameter. Rather than being bound to a value supplied in between call-time parameters, this is bound to the object on the left of the call-time dot.

PART 2. The Parameter “This”

Rules of how this gets a binding resemble rules of how positional function parameters get their bindings.

COPYRIGHT © 2018 CodeStates
COPYRIGHT © 2018 CodeStates

Let’s assume you’re running your code with a debugger and paused on a line that refers to this.

  1. Scan outward from the keyword this and look for the closest enclosing braces that represent a function body. (* Ignore braces that don’t represent function bodies like braces for object literals and if blocks)
  2. After finding the function definition where this appears, look for where the function is called. (* In the debugger, you can find that place by looking one step down in the call stack.)
  3. Inspect the syntax of how the function is being called to see which pattern is being followed. (* There are only five different patterns for how the keyword this can appear in your code. Each of these patterns is associated with a specific rule, which the interpreter uses to determine what this gets bound to inside the function for the invocation. After invocation pattern is used, you can predict which interpreter will bind to this.)
COPYRIGHT © 2018 CodeStates

[Note] This blog post is written based on a lecture from CodeStates.

Thanks for reading! 💕 If you like this blog post, please clap👏

--

--