2014-09-06 56 views
0

我正在一个角度的项目,我有一个工厂提供一些全球数据库方法。我在jsfiddle中测试了它,并且它可以工作,但我想知道它是否是正确的方式。正确的方法来引用另一个属性的js属性

所以这里是jsFiddle

function DB() { 
return { 
    newRecord: function() { 
     //create new record 
     var id = 3; 
     //this is the part I am wondering about 
     //is it ok to use this in this way?? 
     this.setCurrentRecordId(id); 
    }, 

    setCurrentRecordId: function (id) { 
     alert('setting id'); 
     return localStorage.setItem('id', id); 
    }, 

    getCurrentRecordId: function() { 
     return localStorage.getItem('id'); 
    } 
} 
} 

var dbStuff = new DB(); 

dbStuff.newRecord(); 

alert(dbStuff.getCurrentRecordId()); 

就像我说的,它似乎在工作;只是想知道有没有更好的方法。

谢谢!

+1

是关于这一行的问题:'this.setCurrentRecordId(id);'如果是这样,这是正确的,是的。 – 2014-09-06 17:23:58

+0

是的,是的,抱歉的混乱! – Panda4Man 2014-09-06 17:43:51

回答

1

使用JavaScript的constructor functions将下面的“标准”的方式:

function DB() { 
    this.newRecord = function() { 
     var id = 3; 
     // yes, since you invoked the DB constructor using 
     // using the new keyword, this will be pointing to 
     // the created instance 
     this.setCurrentRecordId(id); 
    }; 

    this.setCurrentRecordId = function (id) { 
     alert('setting id'); 
     return localStorage.setItem('id', id); 
    }; 

    this.getCurrentRecordId = function() { 
     return localStorage.getItem('id'); 
    }; 
} 

var dbStuff = new DB(); 

dbStuff.newRecord(); 

alert(dbStuff.getCurrentRecordId()); 

如果您需要引用实例在回调或其他一些情况,即上下文失去了处理这个问题的两种常见模式。

无论是存储这个参考(认为是“丑”一些,虽然很方便):

function Ctor(){ 
    var self = this; 
    this.getSomething = function(id){ 
     asyncThing(id).then(function(result){ 
      // here, `this` will refer to the global object 
      self.doSomethingWith(result); 
     }); 
    }; 
    this.doSomethingWith = function(result){ 
     // do something 
    }; 
} 

或者使用.bind()创建一个新的功能与预定义的语境:

function Ctor(){ 
    this.getSomething = function(id){ 

     var processResult = function(arg){ 
      this.doSomethingWith(arg); 
     }.bind(this); // bind sets the function's context no matter where you'll use it 

     asyncThing(id).then(processResult); 
    }; 
    this.doSomethingWith = function(result){ 
     // do something 
    }; 
} 
+1

这些方法的“标准方式”是使用原型:-) – Bergi 2014-09-06 17:27:36

+1

@Bergi虽然非常真实,但它可能会让人们对第一件事情感到困惑:) – m90 2014-09-06 17:29:00

+0

首先抛出原型,然后抛出[回调松动他们的'''上下文](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback)在他们:-) – Bergi 2014-09-06 17:30:21

0

由于您使用localstorage,因此没有任何问题。

function DB() { 
return { 

    setCurrentRecordId: function (id) { 
     alert('setting id'); 
     return localStorage.setItem('id', id); 
    }, 

    getCurrentRecordId: function() { 
     return localStorage.getItem('id'); 
    } 
} 
} 

var dbstuff = new DB(); 

dbstuff.setCurrentRecordId(3); 
dbstuff.getCurrentRecordId() // 3 
相关问题