问题
I've been running the below code and I notice that when running in devtools, obj.hi = 'default', while when running with iojs 3.3.1 with harmony arrow functions as an arg on my machine, obj.hi = 'foo'. "This" is the window when in devtools, while "this" is the object in iojs. Is it generally good practice to avoid using arrows with .call to avoid this?
'use strict'
let obj = {
hi: "default"
}
let foobar = () => {
console.log(this)
this.hi = "foo"
}
foobar.call(obj)
console.log(obj)
回答1:
See Arrow Functions on MDN:
Since this is already bound lexically, invoking an arrow function through the call() or apply() methods can only pass in arguments, but has no effect on this:
So you can use call
and apply
with arrow functions, but you can't influence their this
value: they take this
from the containing scope. The fact that you can dynamically change this
with io.js just indicates that it is broken with regards to this part of the specification.
来源:https://stackoverflow.com/questions/37445878/using-arrow-functions-with-call-this-varies-based-on-if-in-devtools-or-ioj