Home » Odeon Blogs » Bogdan, Methodical Coder »

Javascript assignment by reference vs object cloning

Javascript assignment by reference vs object cloning

I run into a problem recently when trying to validate some fields using Javascript

  1. var opt = {
  2. url: '/users/ajax/check/username/',
  3. preloading: function(obj){
  4. ...
  5. }

  6. $('#id_username').inputChecker(opt);

  7. var opt2 = opt1;
  8. opt2.url = '/users/ajax/check/password/';
  9. $('#id_pass1').inputChecker(opt2);

In JavaScript, when an object variable is assigned to another, it is assigend by reference. That means, both variables point to the same object. This has the implication that if a one variable's property is changed, it is changed in the other variable as well.

So, when I assign to opt2.url a value, op1.url received the same value. This may be the required behavior sometimes, but not here.

In this case, the solution would be to clone the object. Here's the code:

  1. var opt2 = $.extend({}, opt);
  2. opt2.url = '/users/ajax/check/password/';
  3. $('#id_pass1').inputChecker(opt2);

http://stackoverflow.com/questions/122102/what-is-the-most-efficent-way-to-clone-a-javascript-object

Category: Javascript



Leave a Comment :

(required)


(required)




(required)




(required)





Page generated in: 0.19s