出于单元测试的目的,我想检查特定函数是否已被绑定.
function foo() {}
var bar = foo.bind(context);
assertBound(bar); // --> true
assertBound(foo); // --> false
Run Code Online (Sandbox Code Playgroud)
有没有办法检查bar
是否已绑定不需要模拟bind
函数?
虽然如何从函数中获取[[boundthis]]是要求获取[[boundthis]]
,我想知道只是检查它已被绑定.
{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#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 '
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)
归档时间: |
|
查看次数: |
210 次 |
最近记录: |