0

I am surprised that this generates an error:

var encode = (new TextEncoder()).encode;
encode("This is a test.");

The error message is TypeError: Illegal invocation. I would think that this would be equivalent to

(new TextEncoder()).encode("This is a test.");

Aside from assigning the method to a variable and then invoking it using the name of the variable I assigned it to, I mean, I would think that they're equivalent. Why do I need to go through the trouble of creating a new TextEncoder object, assigning it an identifier, and then calling encode from that identifier?

Melab
  • 2,016
  • 5
  • 23
  • 40
  • Maybe because the `this` scope is lost (or "wrong") when you assign the method to a variable? Try `let encode=(let encoder=new TextEncoder()).encode.bind(encoder);`? – Passerby Sep 08 '19 at 02:39
  • @Bergi This is not a duplicate. I don't even mention `this`! – Melab Sep 08 '19 at 05:08
  • @Melab but when understanding how the `this` keyword works, you will see why the two expressions are not equivalent – Bergi Sep 08 '19 at 05:09
  • @Bergi The code that you suggested I try results in a `SyntaxError` with the message `Unexpected identifier`. – Melab Sep 09 '19 at 20:14
  • @Melab I didn't suggest any code? – Bergi Sep 09 '19 at 20:18
  • @Melab Yes, the code suggested by @Passerby doesn't work. He meant something like `const encoder = new TextEncoder(); const encode = encoder.encode.bind(encoder);`. Alteratively, `const encode = TextEncoder.prototype.encode.bind(new TextEncoder);` or `const encode = (encoder => encoder.encode.bind(encoder))(new TextEncoder);`. – Bergi Sep 09 '19 at 20:21
  • @Bergi The question that this is marked as a duplicate of is much broader than this one. – Melab Sep 09 '19 at 22:52
  • @Bergi I thought Passerby was you. – Melab Sep 09 '19 at 22:53

0 Answers0