[英]Javascript/ Typescript .bind() get Variable in bound function
[英]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
。
我的版本无法正常工作,因为我使用的是翻译打字稿。 此代码段:
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 "
。
简而言之,您可以获得绑定函数的名称,但是女孩函数没有名称。
如果您正在使用节点(已在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]
..并从那里提取
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.