Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 761
tirithen Avatar asked Sep 02 '16 05:09

tirithen


People also ask

What is constructor in ES6?

A constructor is a function that is called each time an object is created (also referred to as instantiated). The User constructor creates the properties of the object (this.name, this. age, this. email) and assigns them the value of the parameters passed to it (name, age, email).

What is super () in JS?

The super keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor. The super. prop and super[expr] expressions are valid in any method definition in both classes and object literals. The super(... args) expression is valid in class constructors.

What is Subclassing in JavaScript?

Subclassing is a term that refers to inheriting properties for a new object from a base or superclass object. In traditional object-oriented programming, a class B is able to extend another class A . Here we consider A a superclass and B a subclass of A . As such, all instances of B inherit the methods from A .

What is this constructor?

What Does Constructor Mean? A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.


1 Answers

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/

like image 81
Nick Avatar answered Oct 06 '22 01:10

Nick