Is there any difference between: window.localStorage and localStorage?

后端 未结 5 556
执笔经年
执笔经年 2021-01-07 17:46

I have been doing the following:

var store = window.localStorage;
store.setItem()

but now I see code doing this:

localStora         


        
相关标签:
5条回答
  • 2021-01-07 18:24

    "window" is the global object in Javascript, so you can ommit it if there's no chance for a conflict

    0 讨论(0)
  • 2021-01-07 18:27

    Unless you've declared a variable named localStorage in a custom defined scope, they're the same. localStorage refers to window.localStorage. In fact every variable in global namespace can be accessed as window.<variableName>

    For example:

    <script>
    function foo() {
        // here window.localStorage == localStorage
    }
    function foo2() {
        var localStorage = 10;
        // here window.localStorage != localStorage 
        // since you have a local variable named localStorage
    }
    </script>
    
    0 讨论(0)
  • 2021-01-07 18:31

    This is old, but today I may have found a difference.

    I have a React app that was 'forgetting' the localstorage values when I ran it on my server with SSL without the WI DOW . Without SSL, it was working fine.

    I went back and added the WINDOW to all the references to localstorage and the problem disappeared

    0 讨论(0)
  • 2021-01-07 18:35

    there is no difference between the window.localStorage and localStorage the Window is the global object

    the window is the default prefix

    but the correct one is window.localStorage because the localStorage attribute is part of window object.

    0 讨论(0)
  • 2021-01-07 18:41

    Supposedly, window.localStorage makes the localStorage faster to be found than just writing localStorage.

    Storing a reference to it on a variable makes it even faster.

    Anyway, these improvements are negligible on modern browsers. It only becomes useful if performance is being an issue.
    Anyway, you get a possible idea about why it is being done like that.

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