Material based on the lecture by Carlos Scheidegger
We can write to the console (helpful for debugging by calling the log method of the console object). Hint: open up your browser’s developer tools to see the output generated by the examples here.See output in new page.
It has variables which hold values:See output in new page.
To create a local variable, use the keyword
var. Local here refers to the current execution context. When used within a function these variables are private to that function, however, when they are declared outside a function, as in the above example, they are still global. As a general rule: minimize your use of global variables, and never define global variables in a function.
You can execute operations on these variables. Below are a couple of important examples, refer to the MDN documentation for the full list:See output in new page.
Array literals are declared using square brackets and addressed with square brackets and a reference to the index starting with 0:See output in new page.
You can do much more with arrays than shown here, again, check out the MDN documentation. Arrays are very important for data visualization, so take the time to go through this!
Control StructuresSee output in new page.
LoopsSee output in new page.
There is an alternative way of defining functions:See output in new page.
If we create an object with slots that hold functions, this starts to look like methods from Java and Python. If we create a function that returns these objects, this starts to look like class contructors:See output in new page.
Inheritance, without Classes
The special variable
this. When a function is called with a notation that resembles methods in typical object-oriented languages, say
this is bound to the object holding the method (in this case obj). this allows you to make changes to the local object:
So far, so good: we’ve used
this to change the value bound to the x field in the object. That’s pretty convenient.
this with a given object is simple to explain, but sometimes leads to strange behavior. The way it works is that although
obj.someFunction is the syntax to access the
someFunction slot from obj and
someFunction(parameter) is the syntax to call a the function value bound to someFunction with parameter parameter, the syntax
obj.someFunction(parameter) is not equivalent to storing
obj.someFunction to some temporary variable and calling that. In other words, the syntax
Here’s what can go wrong:See output in new page.
Anytime you use this and something goes wrong, the first you should try to check is whether some call in your chain forgot to set the binding by using the right syntax.