view core-javascript/simple-classes.rst @ 150:5118d0e38ba4 core-javascript-latex

$ hg merge core-javascript # into core-javascript-latex
author jf3243
date Tue, 01 Nov 2011 08:58:38 +0000
parents fef162a89a47
children 29c7fe19aeb5
line wrap: on
line source

Simple classes
==============

JavaScript has objects, which through the object tree support
inheritance.  Almost all object-oriented languages have classes and
instances, but JavaScript has neither.  This will be explained later,
along with a discussion of the consequences.

For now our focus is on getting going with object-oriented
programming.  The easiest way to do this is via create.


Definition
----------

Here's a factory function that creates classes.  It returns a function
called *cls*, which in turn when called returns instances.  At it's
heart is *create*, and also *apply* and *arguments*, which we've not
seen before).

.. literalinclude:: /core-javascript-work/library.js
   :language: javascript
   :start-after: start SimpleClass
   :end-before: end SimpleClass


Why *cls*?
----------

We call the returned function *cls* because in JavaScript *class*,
like *function* is a reserved word in JavaScript.  However, in
JavaScript the identifier *class* has no meaning, and cannot be used
in any valid JavaScript program.  It seems that they intended to
provide a built-in class capability, but never got round to it.


Fruit example
-------------

Here's an example of the use of *SimpleClass*.  There's a bug in it,
and I've changed the test so it passes.  Can you find the bug and fix
the example?

.. literalinclude:: /core-javascript-work/test_library.js
   :language: javascript
   :start-after: start SimpleClass
   :end-before: end SimpleClass