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
Question #1
prototype
has the benefit of monkey patching. As the first example shows, the function are added after-the-fact. You can continue this to add or replace any methods you need (though, with fair warning).
Defining objects like #2 is more along the lines of classic OOP. But, then again, monkey patching isn't allowed in all OOP languages.
Question #2
In your 3rd function, you don't even need the get
and set
functions -- name
and age
are public properties (the potential downside to {}
).
var User = {
name: "",
age: 0
};
User.name = 'Bob';
User.age = 44;
console.log("User: " + User.name + ", Age: " + User.age);
When you create an object using {}
(an object literal), {}
is the constructor (varying on browser). But, essentially, no you can't use a constructor in this format.