Mercurial > js4py
view core-javascript/simple-classes.rst @ 213:0ea90a1819c2 default tip
Custom theming
| author | Radomir Dopieralski <radomir.dopieralski@allegro.pl> |
|---|---|
| date | Wed, 27 Jun 2012 16:35:54 +0200 |
| parents | 29c7fe19aeb5 |
| 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
