A
A
Aligatro2018-03-12 05:04:30
JavaScript
Aligatro, 2018-03-12 05:04:30

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}

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-03-12
@Aligatro

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}

Demo.
The object will have access to class methods and pass the instanceof test .
Option 2: You can also override only the constructor:
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}

Demo.
In this case, the class methods will not be available to the object and it will not pass the instanceof test .
Option 3: Static method and direct instantiation.
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}

Demo.
Direct creation of an instance of a class, without the need for an instance to create it.
I think the third or first option is more suitable for you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question