McShaman McShaman - 4 months ago 8
Javascript Question

Test if variable is a specific bound function in using javascript's Function.prototype.bind()

I am trying to work out how to test if a variable is an instance of a specific bound function. Consider the following example:

var func = function( arg ) {
// code here
}

myFunc = func.bind( null, 'val' );

if( myFunc == func ) {
console.log( true );
} else {
console.log( false );
}


Unfortunately this results in false. Is there some sort of way of testing the variable to find out what function it is bound to?

Answer

No, there is not a way to do this. .bind() returns a new function that internally calls the original one. There is no interface on that new function to retrieve the original one.

Per the ECMAScript specification 15.3.4.5, the returned "bound" function will have internal properties for [[TargetFunction]], [[BoundThis]] and [[BoundArgs]], but those properties are not public.

If you tell us what higher level problem you're trying to solve, we might be able to come up with a different type of solution.


If you yourself control the .bind() operation, you could put the original function on the bound function as a property and you could test that property:

var func = function( arg ) {
    // code here
}

myFunc = func.bind( null, 'val' );
myFunc.origFn = func;

if( myFunc === func || myFunc.origFn === func) {
    console.log( true );
} else {
    console.log( false );
}

Demo: http://jsfiddle.net/jfriend00/e2gq6n8y/

You could even make your own .bind() replacement that did this automatically.

function bind2(fn) {
    // make copy of args and remove the fn argument
    var args = Array.prototype.slice.call(arguments, 1);
    var b = fn.bind.apply(fn, args);
    b.origFn = fn;
    return b;
}
Comments