Brett's Blog
Edit     New

Monday, February 23, 2009

Cleaner private instance methods in JavaScript

Though the Relator requires extra code in places, the benefits are made up in readability in being clear what is private or not, as well as avoid needing the cumbersome 'this' everywhere (whose ubiquity makes its role less clear and also often requires adding a line to assign 'this' to 'that' anyways)

Here I point out a way to avoid needing to make a call() on each reference of a private instance method, again drawing from Andrea Giammarchi's approach to private methods, as I have also covered.

By assigning our static method to the scope of 'this' (as we do if we call call() on the method) and assigning the returned function to a private variable, we can get instance methods throughout our class. The disadvantage is that we add one function per instance (as with privileged methods), but the advantages are 1) the method is truly private, and 2) The syntax is cleaner. If you don't care about #2, just call a regular static method (but which can use 'this') with, arg1, arg2);

var Constructor = (function () {var __ = Relator.$();

// Harder setup, more memory, easier calling within the class
function _setupPrivInstanceMethod (that) {var _ = __.method(that);
return function () {
// Easier setup, and less memory, more complex calling within the class
function _privInstanceMethod () {var _ = __.method(this);

function Constructor () {var _ = __.constructor(this);
_.privateInstanceVariable = 5; // Set up an instance variable to prove we're dealing with an instance method below
_.privInstanceMethod = _setupPrivInstanceMethod(this); // add our instance's scope to return a function which is aware of the instance
Constructor.prototype = {
constructor: Constructor,
someMethod : function () {var _ = __.method(this);
_.privInstanceMethod(); // '5'
// more complex call (additional args would get added after 'this'); // '5'
return Constructor;
var a = new Constructor();


Post a Comment

Links to this post:

Create a Link

<< Home

Brett's Blog Web