Browser javascript output doesn't show classname (unlike Node)

52 views Asked by At

Нello! I have the following short bit of javascript:

let DynamicallyNamedClass = className => {
  let F = function() {
    this.v = 'hi';
  };
  Object.defineProperty(F, 'name', { value: className });
  return F;
};
let AmazingClass = DynamicallyNamedClass('AmazingClass');
let amazingInstance = new AmazingClass();
console.log(amazingInstance);

The output here is more or less useful depending on whether this code runs in Node, or in the browser (chrome):

In Node console.log gives me very nice output:

>> AmazingClass { v: 'hi' }

In the browser, not so nice at all:

>> F {v: "hi"}

Why doesn't the browser (chrome) show me the name of this dynamically named class in debug output? Why doesn't Object.defineProperty seem to apply? I can use a much uglier technique to get the dynamic class name to show up:

let DynamicallyNamedClass = className => {
  return eval(
    `let FF = function ${className}() {` +
    `  this.v = 'hi';` +
    `};` +
    `FF;`
  );
};
let amazingInstance = new (DynamicallyNamedClass('AmazingClass'))();
console.log(amazingInstance); // Shows up nicely!

If dynamically naming classes can be achieved, why force such an ugly approach? Why not adopt something closer to what Node uses when displaying the names of classes in debug output? Is there any rhyme or reason here?

0

There are 0 answers