2

Н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?

Gershy
  • 5,378
  • 1
  • 27
  • 38
  • 1
    In Firefox get `Object {v:'hi'}` ...even less informative . No standards for how different environments parse things to the console. – charlietfl Nov 22 '18 at 21:33
  • 1
    Note the defineProperty is working ... `console.log(AmazingClass.name)` – charlietfl Nov 22 '18 at 21:37
  • Try to not assign the function to a variable (`F`). – Bergi Nov 22 '18 at 22:11
  • 2
    Most people don't realise this but `console.log` is non-standard. It is literally not specified in any standard. Each version of `console.log` is implemented however the implementer thinks `console.log` should behave – slebetman Nov 23 '18 at 00:25

0 Answers0