Using arrow functions with .call()? “This” varies based on if in devtools or iojs locally? Should one avoid using arrows with .call?

本秂侑毒 提交于 2019-12-12 20:58:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!