开发者

Is there an equivalent of python's __name__ for a Javascript object

How do I find the string form开发者_高级运维 of an object name in javascript?


function bar(){};
console.log(bar.name);

//Prints 'bar'

This works for functions only, not objects of any other type.

For a CoffeeScript class, you can do this

class Foo
f = new Foo
console.log f.constructor.name
#Prints 'Foo'


If a function is defined using function foo() {…}, you can get its name using foo.toString(). For example:

> window.alert.toString()
"function alert() { [native code] }"

However, if the function is defined anonymously (ex, var foo = function() {…}), then there's no way to get the name foo.

Edit: it turns out the name can be accessed through .name (see Peter Lyons's answer), so using .toString() would be silly (although I'll leave my answer here as it may be instructive).


function A() {};
var a = new A();
a.constructor.name // => "A"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜