0

Facing a Javascript problem that has to be simple. Going nuts.

I declare and assign a variable as usual: 'let that = this'; When running the code in the Chrome debugger, 'this' is defined and has a value, but 'that' remains undefined. I know that 'this' is fickle in Javascript, but we're speaking the line after the assignment.

Any idea of what would happen? This is in a quite simple event handler, don't see where there could be a trap.

I started using Flow and transpiling JS with Codekit. I have the impression that Chrome debugger has gone a bit unstable since, could it be related?

Many thanks!

Screenshot in Chrome debugger

Community
  • 1
  • 1
Eric
  • 243
  • 3
  • 9
  • What happen if you try : let that = $(this); ? – Jimmy Surprenant Oct 12 '18 at 15:46
  • Hmm, are you in `strict` mode ? and is that code inside another function ? and besides that do not use arrow functions for event handling (*`this` is not the element that triggered the event in that case*) – Gabriele Petrioli Oct 12 '18 at 15:50
  • This is a bug in the Chrome debugger. See https://stackoverflow.com/q/37182473/1048572, https://stackoverflow.com/q/36160736/1048572 or https://stackoverflow.com/q/35565980/1048572 for related reports. See the duplicate on *why* `this` gets you undefined and how to fix it. – Bergi Oct 12 '18 at 15:57
  • OK, no, it's not a Chrome bug. It's simply an issue with using a transpiler and source maps. When you enter things in the console, they are *not* transpiled an run in the actual environment, not the code that you see in the source map. – Bergi Oct 12 '18 at 16:11
  • Many thanks for the quick answers. So let that = $(this) gives the same. I am in strict mode, yes. Using the ES5 format for the function does the same. And it is the same problem when using event.target, so not directly related to using this. So maybe Bergi has identified the problem. In that case, the question I have to solve is why the transpiled code does not accept the variable assignment. Will have to look further... Many thanks anyway! E. – Eric Oct 12 '18 at 16:15
  • So tried again without the minification, and in the window of the transpiled (from Flow, but not minified) code. **Now works** seamlessly. Kudos to @Bergi. Quite interesting to know, been going crazy for a few days now on this and other similar oddities... Many, many thanks. E. – Eric Oct 12 '18 at 16:54
  • @Eric The transpiler is not the issue, it just caused the confusion about what the value of `this` is. The problem was the use of the arrow function, with a normal `function` expression the `this` inside change handler will refer to the element. – Bergi Oct 12 '18 at 17:27
  • Hmmm... Will then have to be more careful with these arrow functions! I naively had understood from the ES6 literature that Arrow Functions did not set a scope for this, and therefore that it was somewhat safer than traditional functions. Many thanks, E. – Eric Oct 14 '18 at 08:09

0 Answers0