Fox Amadeus
Fox Amadeus

Reputation: 326

Arrow function vs. bound function

While reading the article I was a bit confused about the following quote.

The problem here is that each time an => is encountered, it creates a new copy of the arrow function.

What did the author mean by a new copy each time? A new copy of what? What is each time? Where can I find a reference which fully encompasses usage and execution flow of arrow function with creating a new copy each time?

It would be clear if the author wrote a new instance of the arrow function. But he wrote a new copy of the arrow function. Moreover please don't give me more simplified explanations in comparison with the MDN of how arrow function works. Just answer why the author wrote copy instead of instance or maybe not instead. And answer where that each time happens in context of his article and code chunks.

Upvotes: 4

Views: 590

Answers (2)

eisbehr
eisbehr

Reputation: 12452

It belongs to the fact that arrow function can't use this the way you might know it from other things. You can't bind or pass any context to an arrow function. And that bind always creates a copy of the function object.

This together explains the example in the article. First off, they use a normal function, to be able to bind this to it. On the the second step, they overwrite the original function object itself with the new copy of the function with the correct binding. This is a huge performance boost, because you only have to do it once, and not on any future call.

An example for the this problem:

function testNormal() {
  // 'this' is the object, passed below by 'bind'
  console.log(this);
}

var testArrow = () => {
  // 'this' is always the current parent
  // there is no way to pass an other value to 'this' in an arrow function
  console.log(this);
}

testNormal.bind({data: 'test'})();
testArrow.bind({data: 'test'})();

Upvotes: 1

pwolaq
pwolaq

Reputation: 6381

const fn = () => {}

is basically the same as old

const fn = (function(){}).bind(this);

Function.prototype.bind returns a new function on every invocation. That's why it is a good idea to store bound function somewhere instead of creating it on every encounter.

Upvotes: 3

Related Questions