Persistent Object using localStorage
It is impossible to know the variable name without passing it separately because the name is not part of the object itself, but only one (of potentially many) signs pointing to that object. Expecting the object to know that variable name is like expecting a building to know which road you drove in on. Besides, specifying the localStorage key separately is a good thing - it allows you to refer to the same key using different names in different parts of the program.

You can get around having your methods show up in for-in loops by using getters instead of properties or prototypes. If you're concerned about compatibility, you can fallback to __defineGetter__.

Here's what I came up with.

function localObject(key) {
    var _this = JSON.parse(localStorage[key] || '{}');
    Object.defineProperty(_this, 'save', {
        get: function () {
            return function () {
                localStorage[key] = JSON.stringify(this);
            };
        }
    });
    return _this;
}


The new is optional - you can write both

var scores = new localObject('highscores'); // and
var scores = localObject('highscores');`.


While the above solution works, it is somewhat inefficient and messy. This stems from the fact that you're trying to get javascript to work the way you want, when what you should be doing is trying to understand how javascript wants to work. Each language has a style, even a personality, and if you're flexible enough to go with it then your code will be shorter, faster, and cleaner. Here's how I would abstract away my JSONification.

function local(key, value) {
    if (value === undefined) {
        return key in localStorage ? JSON.parse(localStorage[key]) : undefined;
    } else {
        localStorage[key] = JSON.stringify(value);
        return value;
    }
}


Now we can write code like this:

var score = local('highscore');
// use score like a normal variable, because it is one. then, eventually:
local('highscore', score);