Object orientation in javascript
Written by my, some time ago. Found it again at the waybackmachine. A javascript 'debugger', written in javascript. Time did change, nowadays every browser got a debugger included. On the other hand, this helped me to remember the object concept of js. I'm leaving this mostly unchanged. Originally it was possible to modify the examples. Didn't find out yet, what I did.
Object Orientation in Javascript - Objects and Instances
Page 1 of 2 Syntax and possiblities of object oriented javascript.
It's written mainly for cpp programmers, who need to get familiar with javascript,
and uses the terminology known by the cpp concept of object orientation.Javascript is simple. To be honest, I don't like Javascript. Sometimes I get the feeling it's just one big flaw. What you write and test in firefox will most likely not run in the internet explorer, if you make it work in explorer6, it doesn't run in explorer7, and so on... But there's no choice. When I needed to get myself familiar with the more advanced bugs of javascript, I had a hard time to get the concept of object orientation with javascript. Not because it would be complicated, but because I simply thought in my much more complex categories, furthermore I wasn't able to find a short tutorial which would had shown just howto make a class, .. So I decided to focus on the differences between cpp and javascript and wrote some code to play around with object orientation. For fun and learning I wrote an interactive debugger, which should show some concepts. If you debug the examples, you hopefully will be able to get some understanding of the object orientation concept in javascript. I'd like to suggest stepping line by line and watching the output. In difference to cpp, there is no public, private, virtual,. There is however the concept of object orientation. First and big difference: in javascript ALL arrays and functions are objects and could be named classes. You can add functions and variables to them, and there's no protection like in cpp.(public/private). Therefore you don't need to declare class variables, you can add "properties" everywhere in your code (to the class as well as to the instance). I'd however consider this bad practice and would like to suggest a cpp like style of declaring all methods and variables of a object within a clearly separated part of your script. Short example:
I would compare the object obj with a namespace. I've named the variable "obj.variable" a "static" class variable, because declaring a class and creating a instance is quite similar and can be mixed with objectproperties: Again according to the book "Javascript, the definitive guide", chapter 8.4, all objects declared as prototypes will be shared in the memory along with all instances of the classes. They will be "unshared", as soon as they are written to. In the hope I made the difference between objects and instances clear, let's proceede with inheritance. |
|