my guide is just a reinforcement by different sayings, bunch of quick tips and links on how to eyeball the determination what 'this'.
function () { console.log(this) }
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
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.