Do ES6 arrow functions have their own arguments or not? [duplicate]

谁说胖子不能爱 提交于 2019-11-27 05:53:35

问题


I don’t know whether arrow functions bind arguments to a lexical scope or not.

Take a look at this example (the same concept can be used for this):

var b = function() { return () => console.log(arguments); };
b(1,2,3)(4,5,6); // different result of chrome vs FF.

When I run this on Chrome, I get [1,2,3], but on Firefox, I get [4,5,6]. What’s going on?


回答1:


From the spec:

Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment.

Therefore, the correct answer would be [1,2,3]. Firefox has fixed the problem in version 43 (bug 889158).




回答2:


No, arrow functions don't have their own arguments, this, super, or new.target.

See the note at 14.2.16 Runtime Semantics: Evaluation:

An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.




回答3:


Arrow functions don't have their own arguments object.

Arrow functions do not expose an arguments object to their code: arguments.length, arguments[0], arguments[1], and so forth do not refer to the arguments provided to the arrow function when called.

Arrow_functions

For this example

var b = function() {
  return () => console.log(arguments);
};

b(1,2,3)(4,5,6);

correct answer should be [1, 2, 3]




回答4:


What's going on is in fact pretty simple. Chrome does not seem to add an arguments object to the scope of the inner (arrow) function, while Firefox does.

This means that the arguments logged in Chrome are the arguments passed to the parent function, which is a "normal" function.

Firefox believes (and in my opinion they're right to) that the arrow functions should also have the arguments object, and thus that is why they log the second set of numbers.

As others said, what Firefox does is against the specification.



来源:https://stackoverflow.com/questions/33288998/do-es6-arrow-functions-have-their-own-arguments-or-not

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