Beginning AngularJS

(WallPaper) #1
ChApter 1 ■ JAvASCrIpt You Need to KNow

Everything is identical, except for the fact that I removed the this keyword from firstName and age. This is an
example of what not to do. As the following output shows, my browser didn’t like it one bit.


Uncaught ReferenceError: firstName is not defined


The moral of the story is this (no pun intended): make sure that you access the current object’s properties via the
this keyword, if you want to avoid unpredictable results.
I cannot delve much into object-oriented programming techniques here, as this is a huge topic that would fill
many books in its own right. However, although I didn’t touch upon it much here, it is worth knowing that JavaScript
does support this paradigm quite well, should you wish to explore it further.


Enumerating Properties

You can use a for in loop to enumerate an object’s properties. This is an easy way to interrogate any object, and it has
many other uses as well. Listing 1-21 provides an example of a for in loop.


Listing 1-21. The for in Loop


<!DOCTYPE html>




JavaScript Primer





Listing 1-21 uses a for in loop to print each property of myObject to the console. It can be extremely handy at
times, though this example isn’t exactly awe-inspiring. All we do here is use the variable prop, which changes with
each pass through the loop, to print the property’s value to the console.

Free download pdf