JavaScript is an object-oriented language that differs
from
Java in significant ways:
Java | JavaScript |
Consists of classes and their instances (objects) |
Consists of objects only, with classes simulated |
Statically typed: Variables must have data types |
Dynamically typed: Variables do not have data types |
Strongly typed: Most type rule violations detected by compiler |
Loosely typed: Errors detected at run-time |
Large language designed for fast execution and type safety |
Lightweight language designed for embedding in other
applications, such as web browsers |
This section shows JavaScript code examples from the
farmer-wolf-goat-cabbage and water jug problems.
JavaScript objects for the FWGC problem are similar to those in our
Java implementation. There are three files:
- FarmerState.js
- FarmerMove.js
- FarmerProblem.js
whose objectives correspond to their Java counterparts.
However, there are no class or interface definitions and, therefore,
there is no class or interface inheritance as in our Java framework.
State objects are represented using
FarmerState.js, shown below
at bottom.
Note the inclusion of
equals and
safe methods along
with
toString.
Shown below is
StateTest.html, which creates and manipulates
some
FarmerState objects:
Here is how the browser renders
StateTest.html.
Move objects are represented using
FarmerMove.js, shown below
at bottom.
Note the inclusion of the
name property and
doMove method
for objects created with the
FarmerMove function, as well as
non-method functions used to support
doMove.
Shown below is
MoveTest.html, which creates and manipulates
some
FarmerMove objects:
Here is how the browser renders
MoveTest.html.
Problem objects are represented using
FarmerProblem.js, shown below
at bottom.
Note the inclusion of familiar properties and methods for problem objects.
Shown below is
ProblemTest.html, which creates and manipulates
a
FarmerProblem object.
It shows a use of the
map method available from JavaScript's
predefined core
Array object.
map takes a function as an argument and applies it to each
element of the implicit array (in this case,
problem.moves),
producing a new array containing the results.
Here is how the browser renders
ProblemTest.html.
The water jug JavaScript files have the same organization as the FWGC
files.
Although the corresponding files do not share formal interface types or
extend the same abstract classes, there is commonality:
- The WaterJugState.js and FarmerState.js files both
provide the equals and toString methods
- The WaterJugMove.js and FarmerMove.js files both
provide the doMove method
- The WaterJugProblem.js and FarmerProblem.js files
both provide the success method and
the name, introduction, initialState, currentState,
and moves properties
This commonality will be exploited by JavaScript code that
implements an interactive problem solver similar to our Java problem solving
framework's
GUI class.
Understanding that code requires more understanding of HTML and the DOM.