I've got a function:
function createOrLoadDB (host) {
var db = JSON.parse( window.localStorage.getItem(host) )
if ( db == null ) {
db = new InitDB(host)
}
else {
db.__proto__ = InitDB.prototype
}
return db
}
That to me seems like it would work, but w开发者_StackOverflow中文版hen I call db.flushDB()
I get
TypeError: Object #<an InitDB> has no method 'flushDB'
Which is funny, because I've got that in my object def:
function InitDB ( host ) {
... stuff
this.flushDB = function () {
window.localStorage.setItem( this.host, JSON.stringify( this ) )
}
... stuff
}
Am, I missing something. The __proto__
made it say #<an InitDB>
, but it still isn't picking up the methods...
Add your flushDB
method to InitDB.protoype
. Otherwise the method will only appear in objects explicitly created by InitDB
.
Something like
function InitDB(host) {
// the init stuff here, minus this.flushDB
}
InitDB.prototype.flushDB = function() {
window.localStorage.setItem(this.host, JSON.stringify(this));
};
精彩评论