开发者

another javascript function object question - more elegant way then using toString()

I turn to you with another Javascript object related question I was not ab开发者_Go百科le to find an answer so far.

I understand that functions are objects and that they do not have names. Instead variables are references to those objects.

> var a = function() {
... console.log('a');
... };
> a
[Function]
> typeof(a)
'function'

All this means that I can not ask a function for its name. I totally agree with that. But there is another case (putting the named function into an array) where I would be interested in the name and it is obviously there.

> var b = [function myname(){console.log('hi');},];
> b[0]
[Function: myname]
> b[0]();
hi
> typeof(b);
'object'
> typeof(b[0]);
'function'

In the later case I am wondering if there is a more elegant way of asking for the name ("myname" in this case) then using toString()?

Cheers, Mark


use the .name accessor

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"

in chrome, console.dir() shows other properties of objects to help you further =]


you can use name property

var b = [ function myname(){console.log('hi');} ];
console.log( b[0].name );


Here's a way to extract the name of a function, using a Function prototype method

Function.prototype.getMyName = function(){
   if (this.name) {
    return this.name;
   }
   var t = this.toString();
   return t.substring(0,t.indexOf('('))
           .replace(/function/i,'')
           .replace(/^\s+|\s+$/,'');
}

var b = [function myname(){console.log('hi');},];
b[0].getMyName(); //=> 'myname'


There is no other way.

The reason why you see the function expression's identifier in console output is that console does call toString() internally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜