- Part 1 of the series.
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:
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.
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
build space ships, and which that automatically calculates speed:
this in the constructor refers to the current
(newly allocated) object.
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:
A method is allowed to access the fields of its associated object
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:
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:
The object bound to the keyword
this depends on the
current method that was invoked.
If called using the
this is bound to the
If called using the ordinary function call form
gets bound to the top-level Window object.
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