Javascript,获取绑定函数的名称

时间:2016-06-29 08:59:44

标签: javascript

我创建了一个函数并将参数绑定如下。

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.,而不是浏览器标准。

3 个答案:

答案 0 :(得分:2)

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)

获取原始名称

答案 1 :(得分:0)

长篇短文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 函数没有名称。

答案 2 :(得分:0)

如果您正在使用节点(现在在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]

..并从那里提取