View Single Post
  #2 (permalink)  
Old January 30th, 2013, 06:52 PM
dharrison2010 dharrison2010 is offline
Registered User
Points: 3, Level: 1
Points: 3, Level: 1 Points: 3, Level: 1 Points: 3, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jan 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default Passing References

Confused...in the book page 88-89 you make reference to passing references is actually being passed by value; however, the code that is used to prove this does not make since to me. Inside the function setName(obj) you are creating a new Object reference, which in other languages would say this is a local variable and will die at the end of the function, thus not reflecting a change on the Object created outside the function. Here is a couple of examples:
HTML Code:
        var person = new Object();
	
	person.name = 'John';
	
	console.log(person.name);
	
	function changeName(obj){
		obj = new Object();
		obj.name = 'Nick';
		return obj.name;
	}
	
	console.log(changeName(person));
	console.log(person.name);
This example produces: John, Nick, John
HTML Code:
        var person = new Object();
	
	person.name = 'John Doe';
	
	console.log(person.name);
	
	function changeName(obj){
		// obj = new Object(); comment out
		obj.name = 'Nick';
		return obj.name;
	}
	
	console.log(changeName(person));
	console.log(person.name);
This example, commenting out the creation of a new Object inside the function, produces: John, Nick, Nick

Which suggest to me that it was in fact passed by reference and not by value.

Any further clarity on this would be appreciated.

Regards,

Darren
Reply With Quote