Is there any difference between: window.localStora

2019-04-18 14:48发布

I have been doing the following:

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

but now I see code doing this:

localStorage.setItem()

Do both do the same thing?

4条回答
我只想做你的唯一
2楼-- · 2019-04-18 15:03

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

查看更多
唯我独甜
3楼-- · 2019-04-18 15:08

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.

查看更多
聊天终结者
4楼-- · 2019-04-18 15:15

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>
查看更多
时光不老,我们不散
5楼-- · 2019-04-18 15:19

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.

查看更多
登录 后发表回答