Mercurial > js4py
view core-javascript/simple-classes.rst @ 207:29c7fe19aeb5
Mark inline code using duble backticks
| author | Radomir Dopieralski <radomir.dopieralski@allegro.pl> |
|---|---|
| date | Thu, 17 May 2012 11:24:48 +0200 |
| parents | fef162a89a47 |
| children |
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
