Morning:
Afternoon:
localStorage ↓localStorageJSON.stringify
JSON.stringifyJSON.parse
JSON.parsethisThe same function can have different values for this depending on how the function is called/invoked.
Try this example live on CodePen.
const app = {
sayYeah() {
console.log(`Yeah, ${this}`)
},
toString() {
return 'app object'
}
}
// When invoked as a method
app.sayYeah() // "Yeah, app object"
// When invoked as an event handler
document
.querySelector('button')
.addEventListener('click', app.sayYeah)
// "Yeah, [object HTMLButtonElement]"
// When manually set with bind
app.sayYeah.bind('w00t')() // "Yeah, w00t"
HTML5 gave us a way to save extra information on a standard HTML Element via the data-* attributes. Basically, you can add any arbitrary information you want, prefixing the name of the attribute with data-. This data is then accessible through JavaScript via the someElement.dataset object, or through CSS via attr(data-*).
<div
id="my-div"
data-name="Awesome div"
data-id="div-1234"
data-color="blue"
data-marshmallows="yummy">
</div>
const myDiv = document.querySelector('#my-div')
myDiv.dataset.name // "Awesome div"
myDiv.dataset.data-id // "div-1234"
myDiv.dataset.color // "blue"
myDiv.dataset.marshmallows // "yummy"
#my-div {
background-color: attr(data-color);
}
div[data-id='div-1234'] {
height: 400px;
width: 400px;
}
localStorage is storage in your web browser that conforms to Web Storage API. It is scoped by domain, meaning other websites cannot access data stored by your website and vice versa. The data in localStorage persists in the browser until removed, even if the browser is closed and re-opened.
To set an item, use localStorage.setItem, and retrieve data using localStorage.getItem. It is important to remember that values stored will always be strings, so it may be use necessary to use the JSON.stringify and JSON.parse methods to set and retrieve non-string data. JSON stands for JavaScript Object Notation. To learn more about JSON, click here.
const myObject = {
thisIsCool: true
}
localStorage.setItem('myObject', myObject)
localStorage.getItem('myObject') // => "[object Object]"
// localStorage saves the result of the implicit myObject.toString() call
localStorage.setItem('myObject', JSON.stringify(myObject))
// calling JSON.stringify converts the object to a JSON string representation
// so it can be stored in localStorage without loss of data
const retrievedObject = localStorage.getItem('myObject') // => "{"thisIsCool":true}"
JSON.parse(retrievedObject) // => {thisIsCool: true}
// JSON.parse converts the retrieved JSON string back into a JavaScript object
Jeffervescence (morning) | Dinoplasty (afternoon)