Search code examples
javascripthistory.js

Why is my saved variable from window.location changing?


I save window.location to a variable but when window.location is changed (History.js) my variable is also changed, why? I am not setting my variable anywhere except on first page request.

(function(){
    var myvar = window.location;

    History.Adapter.bind(window, 'statechange', function(){
        console.log(window.location.pathname);
        console.log(myvar.pathname); // same as window.location.pathname but should be saved data from line 2

        var state = History.getState(),
            options = {
                url: state.url,
                type: 'get',
                success: function(resp, status, xhr) { 
                    $('#wrapper').html(resp); 
                }
            };

        $.extend(options, callbackOptions);
        $.ajax(options);
    });

    $(document).on('click', 'a[data-pjax]', function(e){
        e.preventDefault();

        var self = $(this),
            callback = self.attr('data-pjax');

        History.pushState({ "callback" : callback }, 'Loading page...', self.attr('href'));
    });
})();

I load the page and my current location.pathname is /foo, I click on a pjax link and my new url is /bar. Why is myvar changed when I do it like this? I have no code changing the variable.


Solution

  • typeof window.location
    "object"
    

    location is a reference to an object. When you assign its value to something, you are assigning the reference. Changes to the object will be visible from all references to it.

    If you want to preserve it's previous state, then you need to copy immutable values. You appear to care only about pathname, which is a string…

    typeof window.location.pathname
    "string"
    

    … so store that instead.