断言函数早期受到约束

Mit*_*aro 9 javascript

描述

出于单元测试的目的,我想检查特定函数是否已被绑定.

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

assertBound(bar); // --> true
assertBound(foo); // --> false
Run Code Online (Sandbox Code Playgroud)

有没有办法检查bar是否已绑定不需要模拟bind函数?

笔记

虽然如何从函数中获取[[boundthis]]是要求获取[[boundthis]],我想知道只是检查它已被绑定.

sdg*_*uck 4

{Function}.name在 ES6 中

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

function aFunction () {}
console.log(aFunction.name) // => 'aFunction'
Run Code Online (Sandbox Code Playgroud)

未命名的函数(例如箭头函数)的名称为空字符串:

var aFunction = function () {}
console.log(aFunction.name) // => ''
Run Code Online (Sandbox Code Playgroud)

当使用绑定到上下文时,命名和未命名的函数都Function#bindname开头'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 '
Run Code Online (Sandbox Code Playgroud)

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

function assertBound (fn) {
    return typeof fn == 'function' && fn.name.startsWith('bound ');
}
Run Code Online (Sandbox Code Playgroud)

注意:检查单词bound后面是否有空格很重要,这样我们就不会捕获诸如 之类的函数function boundFunction () {}

______

Function#toString在 ES5 中

知道用户定义的函数是否在 ES5 中绑定的一种巧妙方法是使用Function#toString并查找文本将其转换为字符串'[native code]'

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