Javascript,获取绑定函数的名称

Javascript, get the name of a bound function

本文关键字:函数 绑定 获取 Javascript      更新时间:2023-09-26

我创建了一个函数,并像下面这样绑定了参数。

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


我的版本不能工作,因为我使用的是编译的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成为一个匿名函数,因此它的名称返回undefined。这导致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]

. .然后从那里提取