Question about building the Javascript model

advertisements

I'm working on implementing a Javascript model on a web app that I'm working on. The purpose of the model is to simply hold information about the state of the page. I have come across two different implementations for creating the model and I was wondering which one was the best to use. The first implementation:

var PageInfo = function () {
    this._info = {};
};

PageInfo.prototype = {
    getInfo: function () {
        return this._info;
    },
    setInfo: function (updatedInfo) {
        this._info = updatedInfo;
    }
};

The 2nd implementation:

var pageInfo = function () {
    var info = {};

    return {
        getInfo: function () {
            return info;
        },
        setInfo: function (updatedInfo) {
            info = updatedInfo;
        }
    }
};

Another question I have is about the setInfo() function. When I find myself updating the model, I often want to have the info that I just changed immediately available to me. This has led me to write the setter function as such:

setInfo: function(updatedInfo) {
    info = updatedInfo;
    return info;
}

which I implement in the code like so:

var info = pageInfo.setInfo(newInfo);

Is this ok or should I be implementing it like this?:

pageInfo.setInfo(newInfo);
var info = pageInfo.getInfo();

Just trying to follow best practices and avoid any issues that may come up from using the wrong implementation.


Both implementations are perfectly acceptable. The former will be faster, albeit by a negligible amount, but exposes its internals to the world. This means that any variable that holds a reference to an instance of PageInfo will be able to manipulate the _info property. Generally this is a non-issue as properties that being with an underscore (_) are considered to be private and should be left alone.

The latter implementation makes use of a concept called closure. A closure is formed when a value is returned that maintains a reference to its defining scope. Essentially it means that the info variable is kept alive. Since the variable is "closed over" it's impossible for it to be modified outside of the interface methods that you provide. In my experience this is rarely needed.

In regards to your second question, again either is acceptable. I like the interface for accessor methods to be consistent so I would say that setInfo should not return anything but there are exceptions to every rule. The exception to the rule occurs when the the value returned by getInfo will not be congruent with what was passed to setInfo. That is, if getInfo returns different value than the value passed to setInfo you might want to return the value out of setValue. Otherwise, the caller could simply re-use the value that was passed to setValue instead of calling getValue.