0

I have a ES6 Class in NodeJS 4. In the constructor, I want to modify the prototype of an object, so that it now use this class instance to perform an operation.

But, of course, in the prototype scope, this doesn't refer to the instance of the class i'm creating.

class Generic {
  constructor() {
    this.myClass = util._extend({}, aClass); //shallow copy
    this.myClass.prototype.run = function(fn) {
      var str = this.toString;
      //in the next line, _this_ should refer to the Generic instance.
      this.run(str, fn);
    };
  }

  do() {
    return this.myClass;
  }

  run(str, fn) {
    ...
  }

How can I refer the Generic class instance being created on the myClass prototype scope ?

IggY
  • 3,005
  • 4
  • 29
  • 54
  • So to get this straight, you want `this.toString` to refer to the new instance, but `this.run()` to refer to the Generic instance. It's worth mentioning you really should look at the `extends` keyword and how it works with classes. – Madara's Ghost Oct 25 '15 at 20:11
  • @MadaraUchiha Exactly. – IggY Oct 25 '15 at 20:14
  • 2
    In which case, the `var that = this` solution provided by Oriol is what you're looking for. Please note that it smells to me that your approach is wrong and that this is an [XY problem](http://meta.stackoverflow.com/q/66377/166899). – Madara's Ghost Oct 25 '15 at 20:17
  • 1
    Please please please do not create *classes* as parts of instances. As Madara said, we have no idea what you want to do here, but you are doing it wrong. – Bergi Oct 25 '15 at 22:07

1 Answers1

3

Some options:

  • bind:

    this.myClass.prototype.run = (function(fn) {
      // `this` is the Generic instance.
    }).bind(this);
    
  • that:

    var that = this;
    this.myClass.prototype.run = function(fn) {
      // `that` is the Generic instance.
    };
    
  • Arrow functions:

    this.myClass.prototype.run = fn => {
      // `this` is the Generic instance.
    };
    
Oriol
  • 274,082
  • 63
  • 437
  • 513