断言函数早期受到约束

时间:2015-10-15 14:04:43

标签: javascript

描述

出于单元测试的目的,我想检查特定功能是否已绑定。

实施例

function foo() {}
var bar = foo.bind(context);

assertBound(bar); // --> true
assertBound(foo); // --> false

问题

是否有人检查bar是否已绑定且不需要模拟bind函数?

备注

虽然How to get [[boundthis]] from function要求获取[[boundthis]],但我想知道只是检查它已被绑定。

2 个答案:

答案 0 :(得分:4)

ES6中的

{Function}.name

在ES6中,所有函数都被赋予静态name property

function aFunction () {}
console.log(aFunction.name) // => 'aFunction'

箭头函数之类的未命名函数的名称为空字符串:

var aFunction = function () {}
console.log(aFunction.name) // => ''

使用Function#bind绑定到上下文时,命名和未命名函数的name前面都有'bound '

// Named function
function aFunction () {}
var boundFunc = aFunction.bind(this)
console.log(boundFunc.name) // => 'bound aFunction'

// Unnamed function
var anotherFunc = function () {} // or `anotherFunc = () => 0`
var anotherBoundFunc = anotherFunc.bind(this)
console.log(anotherBoundFunc.name) // => 'bound '

我们可以使用它来查看函数是否绑定:

function assertBound (fn) {
    return typeof fn == 'function' && fn.name.startsWith('bound ');
}

注意:检查单词bound在重要之后是否有空格,以便我们不会捕获像function boundFunction () {}这样的函数。

______

ES5中

Function#toString

了解ES5中是否绑定了用户定义函数的一种hacky方法是使用Function#toString将其强制转换为字符串并查找文本'[native code]'

function assertBound (fn) {
    return typeof fn == 'function' && fn.toString().indexOf('[native code]') > -1;
}

答案 1 :(得分:2)

来自http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.5

  

使用Function.prototype.bind创建的函数对象没有   原型属性

这是一个可能的测试:

function assertBound(obj) {
  return typeof obj==='function' && 
         typeof obj.prototype==='undefined';
}

<强>段:

&#13;
&#13;
function foo() {}

function assertBound(obj) {
  return typeof obj==='function' && 
         typeof obj.prototype==='undefined';
}

var context= {},
    bar1 = foo,
    bar2 = foo.bind(context);

console.clear();
console.log(assertBound(foo));      //false
console.log(assertBound(bar1));     //false
console.log(assertBound(bar2));     //true
console.log(assertBound(context));  //false
&#13;
&#13;
&#13;

相关问题