我创建了一个函数并绑定参数,如下所示。
function myFunc(){}
let boundFunc = myFunc.bind(argument);
但是随后我将这个绑定函数作为参数传递给另一个函数,我需要在其中获取名称。以下:
function doTheThing(callable){
console.log(callable.name + " did the thing");
}
doTheThing(boundFunc);
打印出
bound did the thing
而不是 myFunc did the thing
。有没有办法获取绑定函数的名称?
callable.caller
导致 Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.
并且不是浏览器标准。
Google Chrome v 51.0.2704.103 给出了不同的结果:
function myFunc(){}
let boundFunc = myFunc.bind(null);
function doTheThing(callable){
console.log(callable.name + " did the thing");
}
doTheThing(boundFunc);
它会打印
bound myFunc did the thing
,因此您可以通过 callable.name.substring(6)
获得原始名称
长话短说
callable.name
确实有效,并产生了bound myFunc
。
我的版本无法工作,因为我使用的是转译的打字稿。这个片段:
class MyClass{
static doTheThing(callable) {}
}
let myFunc = MyClass.doTheThing.bind(null);
function handleCall(callable){
console.log(callable.name)
}
handleCall(myFunc);
产生:
var MyClass = (function () {
function MyClass() {
}
MyClass.doTheThing = function (callable) {};
return MyClass;
}());
var myFunc = MyClass.doTheThing.bind(null);
function handleCall(callable) {
console.log(callable.name);
}
handleCall(myFunc);
关键是行
MyClass.doTheThing = function (callable) {};
这使得 MyClass.doTheThing
成为一个匿名函数,因此返回其名称未定义。这会导致 callable.name 返回 "bound " + undefined
或 "bound "
。
所以简而言之,你可以获得绑定函数的名称,但是 girl 函数没有名称。
如果您使用的是 Node(现已在 v9.2.0 上测试),请尝试
import util from 'util'
function myFunc(){}
let boundFunc = myFunc.bind(null)
let functionInfo = util.format(boundFunc)
console.log(functionInfo) // [Function: bound myFunc]
..并从那里提取它
您可以比较绑定函数,看看它是否与原始“未绑定”函数相同。 虽然这样做的方式有点绕。首先使用
new
创建绑定函数的实例,然后与该实例构造函数进行比较,并将其与“原始”函数进行比较:
instance.constructor === originalFunction
这是一些示例代码:
function funcA(aNumber) {
let result = aNumber * 2;
return result;
}
function funcB(aNumber) {
let result = aNumber * 3;
return result;
}
// binding above functions with different arguments
let boundFuncA = funcA.bind(null, 2);
let boundFuncB = funcB.bind(null, 3);
let secondBoundFuncB = funcB.bind(null, 4);
// making instances of bound functions for comparison with "originals".
let instanceOfBoundFuncA = new boundFuncA();
let instanceOfBoundFuncB = new boundFuncB();
let instanceOfSecondBoundFuncB = new secondBoundFuncB();
let instanceOfFuncB = new funcB();
//comparing in different ways.
console.log(instanceOfBoundFuncA.constructor === funcA); // true
console.log(instanceOfBoundFuncA.constructor === funcB); // false
console.log(instanceOfBoundFuncB.constructor === funcB);// true
console.log(instanceOfFuncB.constructor === funcB); // true
console.log(instanceOfBoundFuncB.constructor === instanceOfSecondBoundFuncB.constructor); // true
您可以检查绑定函数是否与“root”函数相同,即使它绑定了参数。甚至两个绑定函数也可以相互关联,只要它们具有相同的“根”函数即可。
原作者和解决方案可以在这里找到: 原创