Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect conversion of fat arrow function #9

Open
elijahdorman opened this issue Jan 17, 2015 · 0 comments
Open

Incorrect conversion of fat arrow function #9

elijahdorman opened this issue Jan 17, 2015 · 0 comments

Comments

@elijahdorman
Copy link

A fat arrow function binds to the local execution context differently. Execute the following in FF:

var __slice = Array.prototype.slice;

var extendWithFunc = function (fn, obj) {
  return fn.apply(obj, __slice.call(arguments, 2));
};

var myExtend = () => {
  this.newData = __slice.call(arguments, 0);
  return this;
};

var newObj = extendWithFunc(myExtend, {some: "object"}, "a", "b", "c");

Notice that if you inspect the value of 'newObj' it is Window. This is because the fat arrow does something much closer to a .bind(this) behind the scenes. Inside of 'extendWithFunc', the function application is ignored (because .bind() uses a special [[Call]] and [[BoundThis]] that cannot be overridden). Therefore, when 'myExtend' is called, the 'this' is the execution context of the global where 'myExtend' was defined (which happens to be Window).

Implementing fat arrow in ECMAScript5.1 as the following is probably closer to accurate.

[1, 2, 3].map(function(n) { return n * 2; }.bind(this));

According to the draft spec from mozilla http://people.mozilla.org/~jorendorff/es6-draft.htm

14.2.17 Runtime Semantics: Evaluation

ArrowFunction[Yield] : ArrowParameters[?Yield] => ConciseBody

  1. If the code of this ArrowFunction is contained in strict mode code or if any of the conditions in 10.2.1 apply, then let strict be true. Otherwise let strict be false.
  2. Let scope be the LexicalEnvironment of the running execution context.
  3. Let parameters be CoveredFormalsList of ArrowParameters[?Yield].
  4. Let closure be FunctionCreate(Arrow, parameters, ConciseBody, scope, strict).
  5. Return closure.

NOTE Any reference to arguments, super, or this within an ArrowFunction are resolved to their bindings in the lexically enclosing function. Even though an ArrowFunction may contain references to super, the function object created in step 4 is not made into a method by performing MakeMethod. An ArrowFunction that references super is always contained within a non-ArrowFunction and the necessary state to implement super is accessible via the scope that is captured by the function object of the ArrowFunction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant