Answer the question
In order to leave comments, you need to log in
How to set the name of the object returned by a class method in es6?
I understand that this is an addiction, but I'm wildly interested.
How do I make the "createSomeObj" method return a named object, either with the name of the class it was called from, or with a newly assigned one.
class myClass {
constructor() {
this.createSomeObj = this.createSomeObj.bind(this);
}
createSomeObj() {
var newObj = {1:1, 2:2};
return newObj
}
}
var instance = new myClass();
console.log(instance.createSomeObj()) // should be 'myClass' {1:1, 2:2}
Answer the question
In order to leave comments, you need to log in
Option 1: Created objects can override the __proto__ property , or take it from an instance of the class:
class myClass {
createSomeObj() {
const newObj = { 1: 1, 2: 2 };
newObj.__proto__ = this.__proto__;
return newObj;
}
}
const instance = new myClass();
const instanceOfInstance = instance.createSomeObj();
console.log(instanceOfInstance.createSomeObj()); // myClass {1: 1, 2: 2}
class myClass {
createSomeObj() {
const newObj = { 1: 1, 2: 2 };
newObj.__proto__.constructor = myClass;
return newObj;
}
}
const instance = new myClass();
console.log(instance.createSomeObj()); // myClass {1: 1, 2: 2}
class myClass {
constructor(props) {
Object.keys(props).forEach(key => this[key] = props[key]);
}
static createSomeObj() {
return new myClass({ 1: 1, 2: 2 });
}
}
console.log(myClass.createSomeObj()); // myClass {1: 1, 2: 2}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question