Your first example was an object literal:
var person = {
name: "Bob",
//etc
};
You've created a single object called person, and that's that. The concept of creating new persons has no meaning.
If you want to create something that can be used to create more objects at will, you'd use a function, like your second example.
Note though that functions intended to be used as a constructor start with a capital letter by convention. Also note that when you set a function inside of your constructor using
this.functionName = function() .....
this creates a privileged function, since it has access to both public, and private members. If this set function only needs access to public properties, it would usually be added to the function's prototype
. Here's how the whole thing might look
function Person() {
this.name = "";
this.age = 0;
};
Person.prototype.set = function(name,age) {
this.name = name;
this.age = age;
}
And here's what a privileged method might look like
function Person() {
var localData = "Hello";
this.showPrivateData = function() {
alert(localData);
};
this.name="";
this.age=0;
};
localData
is local to the Person
function, and cannot be accessed as a property on instances of Person; however, the showPrivateData
function, and any other privileged functions you might add, would form a closure over it, and have access to it.
Finally, note that constructor functions can take parameters:
function Person(name, age) {
this.name= name;
this.age= age;
};