Functions / new

Hi - can anyone explain to me what is the difference between the two codes below in relation to how the ‘friend’ variable is assigned, more specifically I am trying to understand what exactly ‘new’ does behind the scenes, apart from the obvious answer that it creates an object :

function Person(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}

[COLOR="#FF0000"]var friend = new Person(“Nicholas”, 29, “Software Engineer”);[/COLOR]
friend.sayName(); //”Nicholas”
function Person(name, age, job){
//create the object to return
var o = new Object();
//optional: define private variables/functions here
//attach methods
o.sayName = function(){
alert(name);
};
//return the object
return o;
}

[COLOR="#FF0000"]var friend = Person(“Nicholas”, 29, “Software Engineer”);[/COLOR]
friend.sayName(); //”Nicholas”

The new keyword instantiates an object, running the code in the “function” as a constructor. Your examples are a bit odd. Since you’re returning an object, you probably wouldn’t need to call it with new. See Crockfords articles for details on this, I know it can be confusing:

http://javascript.crockford.com/private.html
http://javascript.crockford.com/prototypal.html
http://www.crockford.com/javascript/

Hi,
In the first function, alert(this.name); displays the value of the property “'name” of the object.
In the second function, alert(name); displays the value of the parameter “name” passed to the function.
So, you can get different results if the “name” property is set different, like: o.name = ‘my’+ name;
The ‘new’ creates a new instance of that object, so, you can use multiple instances of the same object, in separated variables.

Hi - thanks for the documentation and the explanations, I think I understand now that the second example is a pattern used for specific circumstances for example where data security is an issue whereby there is no way to access any of it’s data members without calling a method - otherwise one should create instances using the ‘new’ keyword and by doing so you can also make use of inheritance when creating custom objects.