These are excerpts from Nicholas Zakas book which im not clear about, please help me understand.
function setName(obj) {
obj.name = “Nicholas”;
obj = new Object();
obj.name = “Greg”;
}
var person = new Object();
setName(person);
alert(person.name); //”Nicholas”
The local object obj is dead in the heap after function exits ( same when it returns the obj too? )
person and obj are copies or reference to each other as an single object in heap ?
he says “When obj is overwritten inside the function, it becomes a pointer
to a local object. That local object is destroyed as soon as the function finishes executing” .
Then , in he explains factory pattern as following :
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
since now o is local object ,and he said ” That local object is destroyed as soon as the function finishes executing” . so when functions returns o which is a local object and if i
var foo = createPerson(bla,18,student);
then foo is a reference to a local object which must be dead by then . Please clarify the concept of “returning local objects in functions “
Sorry for the long post , mods please edit and condense if needed .
When the first line of
setNameruns theobjreference points to thepersonobject that was created outside the function – this object has its name set toNicholas. So at this stageobjis a copy of the referencepersonthat was created outside the function.When the second line of
setNameruns, the localobjreference is reassigned to point to a new object, so whenobj.nameis called on the third line it is this new object which has its name changed toGreg. Thepersonobject is unaffected by this change of name.In the factory function, it is not correct to say that the ‘local object is destroyed as soon as the function finishes ‘ – the local reference to the object is destroyed, but the object itself was created on the heap and still exists. If the factory function did not
return oon the last line, then this object would be garbage collected because no references to it would exist once the function returned, howeverois not garbage collected because a reference to it is returned by the function.