Here is an example of the practical significance of the difference and how it can bite you if you do not realize it (document.location is the object, and document.location.href is the string):
We use the MonoX Social CMS ( http://mono-software.com ) free version at http://social.ClipFlair.net , and we wanted to add the WebPart language bar on some pages to localize them, but on some others (e.g. , in discussions) we did not want to use localization. Thus, we made two main pages for use on all of our .aspx pages (ASP.net), in the first of which we had the WebPart language bar, and the other had the following script to remove / lng / el -GR and t .d .. from the URLs and show the default language (English in our case) instead of these pages
<script> var curAddr = document.location; //MISTAKE var newAddr = curAddr.replace(new RegExp("/lng/[az]{2}-[AZ]{2}", "gi"), ""); if (curAddr != newAddr) document.location = newAddr; </script>
But this code does not work, the replace function simply returns Undefined (without exception), so it tries to go to the statement x / lng / el-GR / undefined instead of going to the URL x. Testing it with the Mozilla Firefox debugger (F12) and moving the cursor over the curAddr variable, it showed a lot of information instead of some simple string value for the URL. Selecting Watch from this pop-up that you could see in the watch bar, he wrote “Location → ...” instead of “...” for the URL. It made me realize that this is an object.
One might expect a replacement to throw an exception or something like that, but now that I was thinking about it, the problem was that he was trying to call some kind of non-existent "replace" method on the URL object, which seems to be , just returns ", undefined" in Javascript.
In this case, the correct code is:
<script> var curAddr = document.location.href; //CORRECT var newAddr = curAddr.replace(new RegExp("/lng/[az]{2}-[AZ]{2}", "gi"), ""); if (curAddr != newAddr) document.location = newAddr; </script>
George Birbilis Aug 20 '14 at 12:09 on 2014-08-20 12:09
source share