Copy-constructor test in Javascript

Nov 27 2008

After posting about assigning objects in Python only copies the reference and does not clone the object, I wanted to verify if the behavior happened in Javascript. Here is the code:

  1. var myClass = function() {
  2.   this.text = '';
  3.   this.say = function() {
  4.     console.log(this.text);
  5.   }
  6. }
  7. var A = new myClass();
  8. var B = new myClass();
  9. A.text = 'testing A';
  10. B.text = 'texting B';
  11. A.say();
  12. B.say();
  13. A = B;
  14. A.say();
  15. B.say();
  16. A.text = 'testing A2';
  17. A.say();
  18. B.say();

Here is the output:

testing A
texting B
texting B
texting B
testing A2
testing A2

Both A and B end up pointing to the same instance in memory, while the old A instance is inaccessible.
Demo: http://code.enekoalonso.com/js/tests/copy-constructor-test.html

Related Posts:

  • No Related Post

No responses yet

Leave a Reply