3

I want to dynamically create objects of dynamically named class (sorry JS, I got used to call them classes) via dynamically named anonymous function. In this answer I found out that...

As of ES2015, the function created by an anonymous function expression assigned to an object property takes the name of that object property.

So I tried this code:

// dynamically named constructor function
this['Item'] = function(size) {
  this.size = size;
}
// the creation of new object of arbitrary name
let item = new this['Item']('small')
console.log(item);
console.log(this['Item'].name)

and it works: console screenshot 1

BUT when I am actually using the variable name...

let clsName = 'Item';
// dynamically named constructor function
this[clsName] = function(size) {
  this.size = size;
}
// the creation of new object of arbitrary name
let item = new this[clsName]('small')
console.log(item);
console.log(this[clsName].name)

It is acting weird: console screenshot 2

The task itself is much less of an issue for me then the fact that behavior of obj['string'] and obj[variableWithString] differs. So can anybody please explain this phenomena for me? Shouldn't the result in the second example be the same that was in the first one?

connexo
  • 53,704
  • 14
  • 91
  • 128
UniBreakfast
  • 55
  • 1
  • 7
  • 1
    The sentence you cited is a bit misleading. [It doesn't actually work on a property *assignment*](https://stackoverflow.com/q/36497759/1048572), but rather when you declare an object literal with the function in a property. – Bergi Nov 24 '18 at 19:30
  • 1
    Can you do `console.log(this[clsName].name)` (and for the first example as well)? It seems that in the first example, it's just a debugging aid, not the actual `.name` of the class as mandated by the spec. And the debugging aid (supplied by your specific engine and devtools) might support only static property names, not computed ones. – Bergi Nov 24 '18 at 19:33
  • @Bergi, `console.log(this[clsName].name)` outputs an empty string in both scenarios. It's latest Chrome DevTools. So you think it should be like the second screenshot in both cases, but DevTools is trying to be helpful in the first one but not in the second? – UniBreakfast Nov 24 '18 at 20:01
  • 1
    Yes, the empty string is the expected result for `.name` in both cases (see the linked question). Devtools is (always) trying to be helpful and sometimes derives additional names for functions. Apparently it only does so when you assign to a constant identifier though - `this.Item = …` should have a name in the debugger as well. Notice that the mechanisms of how names are derived do constantly change with engine versions (trying to become more helpful), this is not something you should worry about. – Bergi Nov 24 '18 at 20:07

0 Answers0