Square bracket syntax vs functions for localStorag

2019-01-19 14:09发布

问题:

This question already has an answer here:

  • localStorage - use getItem/setItem functions or access object directly? 4 answers

What is the difference between the following two snippets of code? Is the square bracket syntax an old, deprecated syntax? When I first used localStorage, all the documentation I found definitely said to use the square bracket syntax, but now I can't find any documentation on it at all.

The documented syntax:

localStorage.setItem('hello', 'world');
localStorage.getItem('hello'); // world

The square bracket syntax:

localStorage.hello = 'world';
localStorage.hello; // world

回答1:

This is what the documentation says about it:

Although the values can be set and read using the standard JavaScript property access method, using the getItem and setItem methods is recommended.