Javascript,获取绑定函数的名称
Javascript, get the name of a bound function
我创建了一个函数,并像下面这样绑定了参数。
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]
. .然后从那里提取
相关文章:
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- Jquery:将函数绑定到已绑定元素的点击事件
- 我可以通过使用函数绑定来保留默认值吗?如果没有,为什么
- 这在 Object 方法中不引用对象,而是引用函数绑定到的标记
- 为什么当我尝试将函数绑定到自身时,“this”对象仍然引用窗口
- 如何将函数绑定到使用链接函数创建 HTML 的角度指令
- 将jquery函数绑定到事件
- 将服务中的函数绑定到$scope(错误:无法设置undefined的属性'onChange')
- 使用闭包/函数绑定将自函数作为回调传递
- 如何在 Javascript 中将函数绑定到对象数据成员的更改
- 需要将内部函数绑定到元素的单击事件
- 在Javascript中将对象原型函数绑定到对象
- 将函数绑定到Twitter Bootstrap Modal Ajax Complete
- ng使用一个不识别临时变量形式ng repeat的函数绑定html
- 将函数绑定到baz后调用fn.apply(bar,[])
- 将函数绑定到采用参数的不同事件
- 如何将返回函数绑定到标记角度
- 在IE9中未检测到视图模型函数绑定,但在FF和Chrome中有效
- 如何将函数绑定到ShadowDOM内部的元素
- 将原型函数绑定到此的方式不那么冗长