Skip to content

Instantly share code, notes, and snippets.

@aquaductape
Last active July 2, 2019 16:54
Show Gist options
  • Save aquaductape/e6a42fc26a2637c7761d1036cc9db626 to your computer and use it in GitHub Desktop.
Save aquaductape/e6a42fc26a2637c7761d1036cc9db626 to your computer and use it in GitHub Desktop.
understanding THIS in JavaScript

Understanding THIS

my guide is just a reinforcement by different sayings, bunch of quick tips and links on how to eyeball the determination what 'this'.

Determining THIS in Regular Function Expressions

function () { console.log(this) }

1.

  if called in the form of obj.func()
                       "this" === obj
                                 else
                    "this" === global

Direct copy of tip from Bryan Hughes's Node Summit 2017

2. The this keyword’s value has nothing to do with the function itself, it's how the function is called determines this's value

copy paste from this source

3. What NOT to do. "Eyeball it and look left from the 'dot' and that's what determines what this is"

Naive approach, code example below. Problem is that what if 'this' inside myMehod property is nested inside another function.

const sally = {
  myMethod() {
    const nested = function() {
      console.log(this)
    }
    
    return nested()
  }
}


// this === sally? right?
//  |
//  |
//  V
   sally.myMethod()

Better to use steps 1 or 2. For example, myMethod is invoked which calls nested(), once this is logged, is the nested function an object property? obj.nested()? Nope. It's just a regular function. this is set to global object.

Determining THIS in Arrow Function Expressions

1. Arrow functions don't have a this, and this is determined by lexical scope. In other words, lexical scope is defined by you during author time and frozen by the lexer during compilation.

another link

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