How to get name of JavaScript Class

自闭症网瘾萝莉.ら 提交于 2019-12-05 14:30:56

JavaScript doesn't have classes, it has constructor functions and the prototype chain. Together, they can look a bit like classes, but they really aren't. :-)

No, there's no standard way that hereIsTheMagic can find the string "ns.Test" in your example, not even in ECMAScript 5. For one thing, ns.Test may not be the only property referring to that function (what if you added ns.OtherTest = ns.Test;, for instance).

JavaScript does have the concept of functions having proper names, but there's no standard way to access the proper name of a function, and even if you could, the function you're calling ns.Test is anonymous. The property you've assigned it to on ns has a name (Test), but the function does not.

You could give the function a name:

var ns = {}; // Some namespace
(function() {
    ns.Test = ns_Test;

    function ns_Test() {
    // Constructor of class Test
    }
})();

...which is a good idea, because it helps tools help you, but there's no standard way for JavaScript code itself to get at that name. (Don't do ns.Test = function ns_Test() { ... };, though. It should work, but there are various implementations of ECMAScript that have various bugs related to it. More about that in the article linked above.)


Update: I probably should have said: There are non-standard ways to get at the proper name of a function (ns_Test in my example above).

The easiest of these is the name property on function instances, which is supported by many implementations, including:

  • Firefox's SpiderMonkey
  • Chrome's V8
  • Opera's engine (I don't know its name)
  • Safari's engine (including Safari mobile)

...so alert(ns_Test.name); would alert "ns_Test". But it is non-standard and not supported by any version of JScript (Microsoft's engine), not even the version used by IE9 (now finally released!). Here's a quick tester page: http://jsbin.com/oxuva3

Note that, again that's the proper name of the function (see my example above), not the name of the property you've assigned it to.

If name isn't there, you can use toString() on the function object, which may (or may not) return a string representation of the function (e.g., "function ns_Test() { ... }"). That's completely non-standard, but common on desktop browsers; it doesn't work on several mobile browsers, and probably a bad idea in any case. :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!