Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
function , date object are reference type.but when i change reference value it don't change for other variable?

JavaScript
var date = new Date();
var tyt = date;
date = new Date(); //change date,but don't change tyt


JavaScript
var fun = myfunction;
   var fun2 = fun;
   fun = myfunction2;//change fun,but don't change fun2
Posted
Updated 1-Feb-12 23:47pm
v3

1 solution

You got that a bit wrong :). The second date = new Date(); does not change the first instance created by var date = new Date();, but rather replaces it completely. Thus date is now pointing at (referencing) a new instance of the Date object while tyt is still pointing (referencing) the original instance.
What you are after is an example like this:

JavaScript
var date = new Date();
var tyt = date;
date.setFullYear(2020); // Now that is a change that will also affect tyt since the original instance which tyt also points at is changed

alert(date);
alert(tyt);


Regards,

Manfred
 
Share this answer
 
v3
Comments
[no name] 2-Feb-12 5:56am    
thanks Manfred.
Manfred Rudolf Bihy 2-Feb-12 5:59am    
Why a 4?
[no name] 2-Feb-12 6:02am    
it isn't my vote,my vote is 5.
Manfred Rudolf Bihy 2-Feb-12 6:04am    
In that case I aplogize and gratefully accept your vote! :)
[no name] 2-Feb-12 6:06am    
:D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900