Search code examples
javascriptclassfirefoxecmascript-6spidermonkey

Firefox ES6, get class constructor name


I have problems getting the name of the constructor when using ES6 classes in Firefox. In Chromium it works fine, but Firefox seem to have some kind of bug? In Firefox I only get an empty string back. Anyone that knows of a workaround?

class MyClass {}
let a = new MyClass();
console.log(a.constructor.name);

Solution

  • I think it is a bug (according to the comment below).

    It appears that specifying an explicit constructor exhibits the correct behavior in Firefox (even the latest version 48).

    class MyClassWithConstructor {
      constructor() {
        console.log("Explicit Constructor")
      }
    }
    
    class MyClassWithoutConstructor {}
    
    $('#with').click(function() {
    	let tmp = new MyClassWithConstructor();
    	alert("MyClassWithConstructor name = " + tmp.constructor.name);
    })
    
    $('#without').click(function() {
    	let tmp = new MyClassWithoutConstructor();
    	alert("MyClassWithConstructor name = " + tmp.constructor.name);
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id=with>With Constructor</button>
    
    <button id=without>Without Constructor</button>

    Here's a link to JSFiddle: https://jsfiddle.net/jc7g5crp/