我向您提出了另一个与 Javascript 对象相关的问题,到目前为止我无法找到答案。
我知道函数是对象,并且它们没有名称。相反,变量是对这些对象的引用。
> var a = function() {
... console.log('a');
... };
> a
[Function]
> typeof(a)
'function'
所有这些意味着我无法询问函数的名称。我完全同意。但还有另一种情况(将命名函数放入数组中),我会对名称感兴趣,而且它显然就在那里。
> var b = [function myname(){console.log('hi');},];
> b[0]
[Function: myname]
> b[0]();
hi
> typeof(b);
'object'
> typeof(b[0]);
'function'
在后一种情况下,我想知道是否有一种更优雅的方式来询问名称(在本例中为“myname”)然后使用 toString()?
干杯, 标记
最佳答案
使用 .name 访问器
function helloworld() {}
console.log(helloworld.name); // outputs "helloworld"
var hello = function() {} // anonymous function, add a name
console.log(hello.name) // outputs ""
var hello = function hellow() {} //
console.log(hello.name) // outputs "hellow"
在 chrome 中,console.dir() 显示对象的其他属性以帮助您进一步 =]
关于javascript - 另一个 javascript 函数对象问题 - 比使用 toString() 更优雅的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5367793/