This has been eluding me. Take the following code:
function tSt( val ) {
this.val = val;
}
tSt.func = function( x ) {
return x * 2;
}
tSt.prototype.func = function() {
return tSt.func( this.val );
}
var tmp = new tSt( 5 );
console.log( tmp.func()); // 10
var other = tmp.func;
console.log( other()); // undefined
The reason I want to be able to do this is for something like the following scenario:
(function( funcarr ) {
for ( var i = 0; i < funcarr.length; i++ )
console.log( funcarr[i]());
})([ tmp.func ]);
How can this be accomplished?
Update:
Here’s a potentially more global solution, but I’m not sure if there are any drawbacks to doing it this way:
function tSt( val ) {
this.val = val;
this.func = this.func.bind( this );
}
tSt.func = function( x ) {
return x * 2;
}
tSt.prototype.func = function() {
return tSt.func( this.val );
}
Use Function#bind:
This ensures that whenever
otheris called, thethispointer will betmp.Since
bindis not implemented in all browsers, you may need a polyfill like the one given in the above link. (In fact, I recommend you go all the way and get an ES5 shim.)If you’re willing to abandon prototypal inheritance, which is necessary if you want to pass methods around without remembering to
bindthem, then I instead suggest the module pattern:Indeed, another major benefit of this pattern is you can get private variables:
Now consumers of an
Encapsulatedinstance have no access tomineorprivate, but only topublic.