this in arrow block
snowmagic1 opened this issue · 3 comments
for this statement:
Unlike functions, arrows share the same lexical this as their surrounding code.
can I simply consider
'()=>{}'
equals to
'function(){}.bind(this)'
Simply, no.
() => {}
Equals to:
function() {}.bind(null)
So 'this' refers to nothing inside an arrow block. See here: https://babeljs.io/repl/#?experimental=false&evaluate=true&loose=false&spec=false&code=()%20%3D%3E%20%7B%20this%20%7D
@sakarit that is not accurate.
The truth is, arrow's don't actually directly relate to pre-ES6 equivalent code, because they lexically inherit a this
, arguments
, super
, and new.target
, which is not directly representable pre-ES6. Also, they're not allowed to be called with new
like normal functions. The true pre-ES6 equivalent requires contextual code-rewriting from a transpiler.
Also, note that merely looking at the output of babel is not sufficient to understand exactly what ES6 specifies, as their transpilation algorithms perform intelligent minimal-necessary transformations.
More info about arrow functions: http://blog.getify.com/arrow-this/
Thanks @sakarit and @getify for your response.
so es6 arrow doesn't bind this at all, it's a 'lexical this', while its actual value is determined at runtime by how the nearest outer function is called(default/hard binding etc), which looks very error prone to me.
so my takeaway is - never use this in arrow functions, pass in the context as function parameters instead.