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 _privInstanceMethod.call(this, arg1, arg2);
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 _privInstanceMethod.call(this, arg1, arg2);
var Constructor = (function () {var __ = Relator.$();
// Harder setup, more memory, easier calling within the class
function _setupPrivInstanceMethod (that) {var _ = __.method(that);
return function () {
alert(_.privateInstanceVariable);
};
}
// Easier setup, and less memory, more complex calling within the class
function _privInstanceMethod () {var _ = __.method(this);
alert(_.privateInstanceVariable);
}
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')
_privInstanceMethod.call(this); // '5'
}
};
return Constructor;
})();
var a = new Constructor();
a.someMethod();
0 Comments:
Post a Comment
<< Home