How to save functions in localStorage API HTML5

This question already has an answer here:

  • How to store a javascript function in JSON 5 answers
  • Storing Objects in HTML5 localStorage 25 answers

  • Few observations :

  • Functions don't exist in JSON . Look into the official document json.org.
  • A value can be a string in double quotes, or a number , or true or false or null , or an object or an array but not a method .
  • Why method inside an JSON Object ? Methods is basically used to manipulate the data. You can work with data outside of the JSON object as well.
  • You can use JSON.stringify replacer function to convert the function into string while converting to JSON string.

    DEMO

    var storage = {
    	getListUsers: function() {
    		return {
    			name: 'name',
    			age: 'age'
    		}
    	},
    	active: true,
    	data: []
    }
    
    var json = JSON.stringify(storage, function(key, value) {
      if (typeof value === 'function') {
        return value.toString();
      } else {
        return value;
      }
    });
    
    console.log(json);

    You can set the JavaScript which should be set at localStorage as .textContent of a <script> element, get the .textContent of the element to set at localStorage . You can then set the same text at a different <script> element or convert the text to a data URI which can be posted to other browsing contexts or a server.

    <script id="storage">
    /* Example code */
    
    var storage = {
      getListUsers: function() {
        return {
          name: 'name',
          age: 'age'
        }
      },
      active: true,
      data: []
    }
    </script>
    <script>
    var convert = document.getElementById("storage");
    
    localStorage.setItem("data", convert.textContent);
    
    console.log(localStorage.getItem("data"));    
    </script>
    
    链接地址: http://www.djcxy.com/p/27942.html

    上一篇: 以字符串形式接收对象

    下一篇: 如何在localStorage API HTML5中保存功能