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?

0

There are 0 answers