having fun with code

Copy-constructor test in Javascript

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

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info