Variables store and retrieve values.
- Can take any type of data; string, array, integer, float, etc
A function is a list of instructions to accomplish a well-defined task.
- A functions inputs is called it parameters e.g. someNumber
- A functions output is called the return value
- The above function definition accomplishes nothing by itself
- In order for it to be useful it must be put to work, like so:
3. Parameters & Arguments
As we have already learned, functions can have parameters.
- Function parameters are the names listed in the function definition
- Function arguments are the actual values passed to (and received by) the function
An object is a collection of variables and functions.
- Ideally, the components of an object are put together in such a way that the object represents both the attributes and behaviour of some “thing” being modelled in the program
An object used to represent a stopwatch might contain: A variable to represent hours A variable to represent minutes A variable to represent seconds Functions to manipulate those values: - start() - stop()
- Object variables are called “properties”
- Object functions are called “methods”
|stopwatch||stopwatch.hours (e.g. = 0)||stopwatch.start()|
|stopwatch.minutes (e.g. = 24)||stopwatch.stop()|
|stopwatch.seconds (e.g. = 53)|
Object variables are called “properties” & Object functions are called “methods”
The values that make up an object are called the objects properties.
- Properties are variables that belong to an object, sometimes called “member variables”
- Other than the fact that properties belong to objects, there is little behavioural difference between variables and properties
- A property’s name alone is insufficient to identify an objects property
- This is because properties belong to objects, therefore the object to which the property belongs must also be specified:
stopwatch.hours stopwatch.minutes stopwatch.seconds
Methods are functions that belong to objects, sometimes called “member functions”.
- Member functions are designed to operate directly on the properties of the object to which they belong
- Here is a function which adds five minutes on to the current recorded time
- “this” is recognised as a synonym for “the object to which I belong”
- Since, at this point, the addOnFiveMinutes() function doesn’t actually belong to an object, the “this” doesn’t have much meaning
- We can use:
- The behaviour of stopwatch.update() should be the same as specified for addOnFiveMinutes()
- Now that stopwatch has an update() method, we can invoke it with the following statement:
- As a result, the stopwatch object’s member variables (or properties); “hours” and “minutes”, will be replaced with values that represent a time that is five minutes later