HTML and CSS Reference
In-Depth Information
These two approaches are not exactly equivalent. The second approach will
work when property names are not valid variables names. The dot notation on
the other hand will not work if:
• The property starts with a number.
• The property contains a space or other special character except the underscore
or $ sign.
• The property name is one of the language keywords.
If you are writing code that needs to handle any property name, including ones
you had no say in defining, the square brackets notation should be preferred.
In addition to properties, the example above provides an example of a method being added
to an object. The method increaseAge increments the age property by 1: it can be invoked
as follows:
> obj.increaseAge()
> obj.age
I alluded to the use of the this variable inside the method:
obj.increaseAge = function() {
this .age++;
This is the only thing that separates a function from a method: in a method the special vari-
able this refers to the object itself, and therefore:
is a way of accessing the age property on the object. As we will see in future sections, this
takes on several different meanings depending on context. Understanding the meaning of
this in these different contexts is one of the keys to understanding JavaScript.
Although it is possible to construct objects without any reliance on classes, it is probably
obvious that we are also missing out on the benefits that classes bring.
Search WWH ::

Custom Search