Is there any difference with using only location vs using [removed] across browsers

后端 未结 1 1248
[愿得一人]
[愿得一人] 2020-12-10 07:24

I find myself always writing:

console.log(window.location.href);

without even thinking about it. The majority of answers on SO also write i

1条回答
  •  醉梦人生
    2020-12-10 07:53

    There are some differences.

    In global scope, there is absolutely no difference between them, but in other cases you might get in trouble:

    function () {
      var location = { 'href' : '123' } ;
      console.log(window.location.href) // actual url
      console.log(location.href) // '123'
    }
    

    This stems from the fact that if you write location without prefixing it with window, it will go up through every scope to find a variable named location. Eventually it will find it in window, unless another scope declared one as well. Obviously the reverse is true as well:

    function () {
      var window = { 'location' : { 'href': '123' } };  
      console.log(window.location.href) // '123'
      console.log(location.href) // actual url
    }
    

    I for one prefer to prefix the global variables with window because that way i immediately know they are global and also because when i find a global variable that is not prefixed with window, i know it is a typo missing a var, but that is purely personal preference.

    0 讨论(0)
提交回复
热议问题