Simple Accessors and Mutators in Javascript

Good OOD calls for accessors and mutators, which will save you a lot of time in the long run by giving you hooks to run necessary actions on variable changes as well as abstraction. Sometimes though, it’s a pain in the ass to write accessors and mutators for variables on the off chance that we’ll ever need that abstraction. Here’s a way to make accessors and mutators painlessly:


function Accessor(name) { return function () { return this[name]; }; }
function Mutator(name) { return function (newValue) { this[name] = newValue; }; }

var MyClass = function() {
   this.someVariable = 10;
};

MyClass.prototype.getSomeVariable = Accessor("someVariable");
MyClass.prototype.setSomeVariable = Mutator("someVariable");

var example = new MyClass();
example.getSomeVariable();//10
example.setSomeVariable(12); 

We can even condense a little more:


//Assumes camel case convention
function AddAccessor(Obj, name) { 
 Obj.prototype["get" + ucfirst(name)] = Acessor(name);
 Obj.prototype["set" + ucfirst(name)] = Mutator(name);
}

AddAccessors(MyClass, "someVariable");

MyClass.setSomeVariable(15);
MyClass.getSomeVariable(); //15

And if you don’t mind “polluting” the object prototype it can get even tidier. However, this breaks jQuery (which you don’t want) and requires you to write good code (i.e. use hasOwnProperty) which I’m sure you do anyways if you read this blog.

Leave a Reply

Your email address will not be published. Required fields are marked *


− 2 = seven

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>