Monday 17 January 2011

Javascript assignment by reference vs object cloning

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

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

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

var opt2 = opt1;
opt2.url = '/users/ajax/check/password/';
$('#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:

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

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

No comments:

Post a Comment