在使用javascript的Function.prototype.bind()时测试变量是否是特定的绑定函数

时间:2015-04-23 00:34:33

标签: javascript bind

我正在尝试研究如何测试变量是否是特定绑定函数的实例。请考虑以下示例:

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

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

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

不幸的是,这会导致错误。是否有某种方法来测试变量以找出它所绑定的函数?

4 个答案:

答案 0 :(得分:6)

不,没有办法做到这一点。 .bind()返回一个内部调用原始函数的新函数。该新功能上没有用于检索原始功能的接口。

根据ECMAScript specification 15.3.4.5,返回的"绑定"函数将具有[[TargetFunction]][[BoundThis]][[BoundArgs]]的内部属性,但这些属性不公开。

如果您告诉我们您尝试解决的更高级问题,我们可能会提出不同类型的解决方案。

如果您自己控制.bind()操作,您可以将原始函数作为属性放在绑定函数上,然后您可以测试该属性:

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 );
}

演示:http://jsfiddle.net/jfriend00/e2gq6n8y/

您甚至可以自行创建.bind()替换。

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;
}

答案 1 :(得分:2)

您不能直接执行此操作,因为函数,就像 Objects 一样,通过不再匹配的引用测试它们的相等性,§11.9.3, point 1. f.或{ {3}}

但是,您可以创建一些要测试的自定义属性,例如

function myBind(fn) { // takes 2+ args, the fn to bind, the new this, any other args
    var bind = Function.prototype.bind,
        bound = bind.call.apply(bind, arguments);
    bound.unbound = fn;
    return bound;
}

然后检查用法

function foo(bar) {
    console.log(this, bar);
}

// binding
var fizz = myBind(foo, {buzz:0}, 'baz');
fizz(); // logs {buzz: 0} "baz"

// testing
fizz.unbound === foo; // true

如果你想在两个方向上进行测试,那么你需要将它们 OR 放在一起,如果你要绑定已经绑定的函数,甚至可以考虑循环这些属性

fizz.unbound === foo || fizz === foo.unbound; // true

请注意,只要存在绑定版本,该函数的整个未绑定版本链将不会从内存中释放,而某些浏览器可以释放此内存,具体取决于它们{{1 }}

答案 2 :(得分:1)

绑定前置"绑定"在源函数名称之前。

如果您可以为源函数指定一个明确的名称,那么您可以执行以下操作:

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

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


if( myFunc.name.match(/^(bound\ )*(.*)$/i)[2] === func.name ){

        console.log(true);

}

答案 3 :(得分:0)

感谢您输入@jfriend00和@PaulS。我正在使用一个自动向绑定函数添加未绑定属性的函数。这是我写的精致版本。让我知道你的想法。

// My function
var myFunc = function() {
    return 'This is my function';
};

// Function I'm wrapping my function in
var wrapper = function( fn ) {

    var result;

    if( fn ) {
        result = fn.apply( null, arguments );
    }

    // Any additional logic I want to run after my function
    console.log( 'Ran wrapper logic' );

    return result;

};

// Modified binder method
var binder = function( fn, ths, args ) {

    args = [].concat( ths, args );

    var bound = fn.bind.apply( fn, args );

    bound.unbound = fn;

    return bound;

};

// Bind a wrapped version of my function 
myFunc = binder( wrapper, null, myFunc );

// I can test if my function has ben wrapped
console.log( myFunc.unbound == wrapper );

// And I can run a wrapped version of my function
console.log( myFunc() );
相关问题