There are two ways of declaring a function. Both are valid, but try to use the second method as it keeps the usage of
var to a minimum. Functions can be placed in any order, anywhere in your script file as they are “…” (there is a word for this property … and I forgot!).
Call the function such as
To refer to an object property, there are two notations
Methods are functions that are associated with a particular object.
We have already met the
Object constructor, here are some more alongside their respective literal notation
To create your out constructor, use the following
When defining your own constructor, you are in fact defining a new class.
As we have seen there are various types of variables. Use the
typeof command to return a variable type, such as
A prototype is an object from which other objects inherit properties.
In general, if you want to add a method to a class such that all members of the class can use it, we use the following syntax to extend the prototype
You can create new classes which are children of other classes, which effectively become the parents.
Hence, you can create prototype chains, whereby children and grandchildren etc can access properties and methods belonging to their parents and grandparents etc.
To test whether a child is an instance of their parent, we can use the
Encapsulation is the grouping of an object’s data together with its methods. Encapsulating objects allows us to reuse blocks of code to have a more efficient program.
Up to now, we have been defining public variables in our classes and objects.
To access a private variable, we can define a public method, a getter.
Methods can also be private. Just create a public method that returns the private method.
An indexed array is just an ordered list.
To access the array, we use literal notation with an index based at zero.
To add to the end of an array, we use the
splice() method can be used to remove items from an array. It takes two arguments, both integers, specifying the index to start at, and the number of items to remove.
To copy an array, or part of an array, we use the
slice() method. If there are no arguments, then the whole array is copied. Else, we state two arguments which specify the start and end indexes required.
Arrays can contain any objects, in any combination, even arrays themselves to make multi-dimentional arrays.