Javascript,获取绑定函数的名称
我创建了一个函数,并将参数绑定如下Javascript,获取绑定函数的名称,javascript,Javascript,我创建了一个函数,并将参数绑定如下 function myFunc(){} let boundFunc = myFunc.bind(argument); 但是,我将这个绑定函数作为参数传递给另一个函数,在这里我需要获得名称。以下是: function doTheThing(callable){ console.log(callable.name + " did the thing"); } doTheThing(boundFunc); 打印出bound做的事情,而不是myFunc
function myFunc(){}
let boundFunc = myFunc.bind(argument);
但是,我将这个绑定函数作为参数传递给另一个函数,在这里我需要获得名称。以下是:
function doTheThing(callable){
console.log(callable.name + " did the thing");
}
doTheThing(boundFunc);
打印出bound做的事情
,而不是myFunc做的事情
。有没有办法获得绑定函数的名称
callable.caller
会导致uncaughttypeerror:“caller”和“arguments”是受限制的函数属性,无法在此上下文中访问。
并且不是浏览器标准 Google Chrome v 51.0.2704.103给出了不同的结果:
函数myFunc(){}
设boundFunc=myFunc.bind(null);
函数doTheThing(可调用){
log(callable.name+“做了那件事”);
}
doTheThing(boundFunc)
长话短说可调用。name
确实有效,并生成绑定的myFunc
我的版本不起作用,因为我使用的是transpiled typescript。这个片段:
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返回“绑定的”+未定义的
或“绑定的”
简而言之,您可以获得绑定函数的名称,但girl函数没有名称。如果您使用的是node(现在在v9.2.0上测试),请尝试
。。然后从那里提取它据我所知,没有。
.bind()
返回一个全新的函数。因此,除非您在某个地方持有旧函数的实例,否则无法确定其名称。同样适用于FF 49.0a2。但是,我可以建议对原始名称使用/^bound(.*)$/.exec(callable.name)[1]
,因为如果名称因某种原因与模式“bound…”不匹配,则不会自动失败。我发现该代码段对我也适用,但执行相同操作的原始代码却不适用。@timly您可以发布实际的代码吗?您的问题中的一个无法工作,因为您正在检查callable()
是否返回真实值,但它从来不会返回。还要检查绑定到它的内容。bind
的第一个参数是上下文,也就是您希望this
引用的任何内容。问题中的逻辑并不重要,不确定我为什么添加它。我已经解决了我的问题,我只是写下来回答为什么它不起作用。
import util from 'util'
function myFunc(){}
let boundFunc = myFunc.bind(null)
let functionInfo = util.format(boundFunc)
console.log(functionInfo) // [Function: bound myFunc]