Friday, December 1, 2017

Overcoming JavaScript "this" keyword confusion


The use of the this keyword in JavaScript is confusing. It is not the same as the self variable in Python.

Children can generally get through basic objects and methods in Python and be able to use self.

However, the "this" keyword in JavaScript depends on the way the this keyword is used.

In most cases, the "this" keyword will refer to the object that calls the function/method that the "this" keyword is used in. Wow, that sounds horribly confusing.

Let's break it down.

  • There are different methods within a single object. 
  • One method is called, "preload". 
  • One method is called, "create".
  • To use a variable in both "preload" and "create", I use the word, "this" in front of the variable name.



This is overly simplified, but for a child, I'm focusing on the most common usage.

Problem

The problem at the top of article occurs when you try to use a "this" keyword variable inside of a nested function. The variable "animals" is inside of an anonymous function called by the method forEach(). Oh, no!  This will break the simple explanation of the use of "this".

I explain that "this" only works within a small area, like a shop within a town. As soon as another function is put between the "this.variable" and the top method "create()", you'll have to use some funky techniques to access the variable. 

I'm not sure if the technique at the top of the screen is a best practice or not, but it works and might be a "good-enough" technique for lessons. The code snippet and technique of assigning "this" to "self" are from a mobile game course by Pablo Farias.






No comments:

Post a Comment