The Worst Thing in JavaScript: Losing this

JavaScript is a great programming language. Except when it’s not. What happens to this in certain cases is a good example of JavaScript being not so great.

Consider using setTimeout() to call a function after a delay. We’ve done this several times in the book. In Chapter 11, ​Project: Fruit Hunt​, we used setTimeout() to shake the treasure tree after a two-second delay.

​ setTimeout(shakeTreasureTree, 2*1000);

After 2 seconds (2000 milliseconds), setTimeout() called our shakeTreasureTree() function. We’ve also done this several times for the gameStep() function.

​ setTimeout(gameStep, 1000/30);

What happens if we try to do this with our logMe() method?

​ setTimeout(kungFuMovie.logMe, ...

Get 3D Game Programming for Kids, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.