开发者

Chrome, Javascript, JSON and __proto__ -- where are my methods?

开发者 https://www.devze.com 2023-01-17 09:51 出处:网络
I\'ve got a function: function createOrLoadDB (host) { var db = JSON.parse( window.localStorage.getItem(host) )

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));
};
0

精彩评论

暂无评论...
验证码 换一张
取 消