• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Modern JavaScript for the Impatient: what's this?

 
Greenhorn
Posts: 24
Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Cay,

Question: does your book demystify the nature of "this" keyword in JS ? I came from the Java world, and now struggle to wrap my mind about this conception. While Java's "this" feels natural and straightforward to me, JS's "this", as I learned from various Medium articles, might have different meanings depending on "environment" or something...
I'm both new to JS and impatient (well, who is not these days?), and love paper books. Thanks for the opportunity to participate in the draw.

Take care,
Dmitriy.
 
author
Posts: 284
35
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Dmitriy,

the book does one better than that. It tells you NEVER TO USE this except when implementing a method. Don't use this. Use arrow functions for everything other than methods. And you never need to debug problems caused by this.

Of course, the book also explains how "this" works. But really, don't use it outside methods. For example, I see people use



Now you have to understand how this got bound. Is "this" really a reference to the checkbox? How did that happen? You really have to think about it--it is not obvious.

It is trivial to avoid that mental load:



As long as you understand closures (and you have to understand closures in JavaScript), it is crystal clear what checkbox.checked means.

Cheers,

Cay
 
Yaroslav Ashurin
Greenhorn
Posts: 24
Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, Cay ! Crystal clear !
 
I'm full of tinier men! And a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic