Q:

Proper way to reference js property from another property

I am working on an angular project and I have a factory providing some global database methods. I tested this in a jsfiddle and it works, but I want to know if it is the right way to do it. 
So here's the 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());

Like I said, it seems to be working; just want to know if there is a better way or not.
Thanks!

A:

The "standard" way of using constructor functions in JavaScript would be the following:
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());

In case you need to reference the instance in a callback or some other situation in which context is lost there are two common patterns to deal with this.
Either store a reference to this (considered "ugly" by some, very convenient though):
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
    };
}

Or use .bind() to create a new function with a predefined context:
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
    };
}

