我正在尝试研究如何测试变量是否是特定绑定(bind)函数的实例。考虑以下示例:
var func = function( arg ) {
// code here
}
myFunc = func.bind( null, 'val' );
if( myFunc == func ) {
console.log( true );
} else {
console.log( false );
}
不幸的是,这会导致错误。是否有某种方法可以测试变量以找出它绑定(bind)到什么函数?
最佳答案
不,没有办法做到这一点。 .bind()
返回一个内部调用原始函数的新函数。该新函数没有用于检索原始函数的接口(interface)。
根据 ECMAScript specification 15.3.4.5 ,返回的“绑定(bind)”函数将具有 [[TargetFunction]]
、[[BoundThis]]
和 [[BoundArgs]]
的内部属性,但这些属性不公开。
如果您告诉我们您正在尝试解决什么更高级别的问题,我们也许能够提出不同类型的解决方案。
如果您自己控制 .bind()
操作,您可以将原始函数作为属性放在绑定(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;
}
关于javascript - 使用 javascript 的 Function.prototype.bind() 测试变量是否是特定的绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811479/