📜  我如何使用 javascript 代码示例将构造函数添加到本地存储

📅  最后修改于: 2022-03-11 15:04:12.458000             🧑  作者: Mango

代码示例1
// Extending the Storage object:
Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}



// START HERE:

var dog = { 
   name : '',
   woof : function(){ console.log('woof woof, I am ' + this.name); }
}
dog.name = 'Lovely';

//Store in the localstorage
localStorage.setObject('mydog', dog); 

//Get from the localstorage
var mydog = localStorage.getObject('mydog');
console.log(mydog.name); // prints 'Lovely'
console.log(mydog.woof()); // ootest.html:36 Uncaught TypeError: mydog.woof is not a function(…)