简体   繁体   English

对于 Javascript object 是否有相当于 python 的 __name__

[英]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?如何在 javascript 中找到 object 名称的字符串形式?

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

//Prints 'bar' //打印'bar'

This works for functions only, not objects of any other type.这仅适用于函数,不适用于任何其他类型的对象。

For a CoffeeScript class, you can do this对于 CoffeeScript class,您可以这样做

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() .如果使用function foo() {…}定义 function ,则可以使用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 .但是,如果 function 是匿名定义的(例如, var foo = function() {…} ),则无法获得名称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).编辑:事实证明可以通过.name访问名称(请参阅 Peter Lyons 的答案),因此使用.toString()会很愚蠢(尽管我会在这里留下我的答案,因为它可能具有指导意义)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM