Related resources
- Part 1 of the series.
Forms
Forms are a natural and convenient way to interact with the user. A simple greeting program reads the value out of a field, and changes the value of an element elsewhere:
This program shows a basic model for interactive pages:
add an id to every element in the HTML that will act as
either an input or an output, and then use event handlers to
manipulate the page.
JavaScript can interact with the HTML through the
document.getElementById method.
Constructors
It's tedious to construct objects with the same properties by hand. For example, you might want to create a lot of space ships. Each might have an x coordinate, a y coordinate, an x speed and a y speed:
With this approach, the speed of the ship has to be manually
calculated every time.
A better approach would be to create a SpaceShip that
build space ships, and which that automatically calculates speed:
The keyword this in the constructor refers to the current
(newly allocated) object.
Methods
It is poor design to hard-code the speed of a space ship as a field; the speed of a ship is a function if its velocity. A better approach is to define the speed of a ship using an ordinary function:
JavaScript provides a way to associate functions with objects as "methods."
A method is allowed to access the fields of its associated object
using the this keyword.
To turn a function into a method, one can just assign a function to a field:
Of course, we could also assign the method during object initialization:
Prototypes
A popular (and efficient) way to associate methods with objects is attach methods to a constructor's prototype. Methods attached to a prototype are bound to every instance of an object automatically:
What is this?
The object bound to the keyword this depends on the
current method that was invoked.
If called using the object.method() form,
then this is bound to the object.
If called using the ordinary function call form fun(), then this
gets bound to the top-level Window object.
The fun.call() form allows the caller to specify
the value of this is the first parameter:
Practice: A Calculator
Tie together everything you've learned so far, and make the following calculator work:
Source code: calculator.html