Object Orientation in JavaScript
JavaScript and object orientation has been a long debated issue, and because of the untyped nature of JavaScript many have thought of it as a temporary solution till something that is OO emrges and replaces it, well the current AJAX sites has proved them wrong
in the coming javascript posts i'll try to tap into the OO concepts and how it can be mimicked using JavaScript
this firsrt post is about Classing
i'll first create a simple class
1: function User (){ 2: this.firstName ="Amir";
3: this.lastName = "Magdy";
4: }
and then i'll create code that will instantiate this class and use its attributes
1: var u = new User();
2: // and then i can use its properties
3: alert (u.firstName + ' ' + u.lastName);
what i have managed to do is to use the exposed firstName and lastName attribute it's not the usual way of doing stuff, not the same way that we'd use if we were writing a class in c# for example
well, in c# we'd create a private memeber and access it using an accessor that would give us simple functionality the class would look like this
1: function User(){ 2: _firstName = "Amir";
3: _lastName = "Magdy";
4: this.get_FullName = function { 5: return _firstName + ' ' + _lastName;
6: }
7: }
note that we've simulated the private and public attributes of members in a class so the _firstName and _lastName members are private but because we've used "this" keyword in defining the function get_fullName() we managed to have it as "public" and it can be used like this
1: var u = new User();
2: // and then i can use its properties
3: alert (u.getFullName());
also because of the Nature of JavaScript we can also simulate Constructors, and add setters and getters, Easily see
1: function User (firstName,lastName){ 2: _firstName = firstName;
3: _lastName = lastName;
4:
5: this.get_FullName (){ 6: return _firstName + ' ' + _lastName;
7: }
8:
9: this.set_FirstName(value){ 10: _firstName = value;
11: }
12:
13: this.set_LastName(value){ 14: _lastName = value;
15: }
16: }
17:
18: var u = new User("Amir","Magdy"); 19: u.alert (u.get_FullName());
20: u.set_FirstName ("New"); 21: u.alert (u.get_FullName());