I\'ve been using javascript for a while, but have never learned the language past the basics. I am reading John Resig\'s \"Pro Javascript Techniques\" - I\'m coming up with
If you want to do OOP in JavaScript I'd highly suggest looking up closures. I began my learning on the subject with these three web pages:
http://www.dustindiaz.com/javascript-private-public-privileged/
http://www.dustindiaz.com/namespace-your-javascript/
http://blog.morrisjohns.com/javascript_closures_for_dummies
The differences between 1, 2, and 3 are as follows: 1) Is an example of adding new methods to an existing object. 2) Is the same as #1 except some methods are included in the object in the User function. 3) Is an example of defining an object using JSON. The shortcoming is that you cannot use new (at least not with that example) to define new instances of that object. However you do get the benefit of the convenient JSON coding style.
You should definitely read up on JSON if you don't know it yet. JavaScript will make a lot more sense when you understand JSON.
edit If you want to use new in function #3 you can write it as
function User() {
return {
name: "",
age: 0,
setName: function(name) {
this.name = name;
},
setAge: function(age) {
this.age = age;
},
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
};
}
Of course all of those functions and properties would then be public. To make them private you need to use closures. For example you could make age and name private with this syntax.
function User() {
var age=0;
var name="";
return {
setName: function(name_) {
name = name_;
},
setAge: function(age_) {
age = age_;
},
getName: function() {
return name;
},
getAge: function() {
return age;
}
};
}