-2

I would like to understand how to refer to this in a specific situation, let's say including a "class" inside a "module wrapper".

Have a look at this example:

var MyClass = (function() {

  theClass = function() {
      // Position A
      this.myValue = 3; // some number.
  };

  theClass.prototype.initSomething = function() {
      // Position B
      $(someButton).on('click', this.myCallback);
  };

  theClass.prototype.myCallback = function(event) {
      // Position C
      console.log(??this??.someValue);
  }.bind( ????? /* Position D */);

  return theClass;
})();

var myObject = new MyClass();
myObject.initSomething();

If I create a new instace of theClass, at position A this refers to the newly create object. That's ok.

At position B, this still refers to the newly created object. That's still ok.

The problem I would like to solve happens at position C, where this will refer to the button. Therefore, I would like to bind myCallback() to the newly created object. But, at position D, I am outside of the newly created instance. But I know the original object and the prototype and more. So how could I refer to the newly created object?

peter_the_oak
  • 3,529
  • 3
  • 23
  • 37

1 Answers1

0

You are making a thinking error.

Position D is run only once. This is probably after the page was loaded.

But there are a lot of different this pointers. Every new() will create a new instance and a new this pointer.

If you try to store new this pointers in the wrapping function, you will need to manage a list of pointers.

The elegant way is to organize all bindings inside your newly instanciated object, where you have this information. Like this:

var MyClass = (function() {

  theClass = function() {
      // Position A
      this.myValue = 3; // some number.
  };

  theClass.prototype.initSomething = function() {
      // Position B
      var myBoundCallback = this.myCallback.bind(this);
      $(someButton).on('click', myBoundCallback);
  };

  theClass.prototype.myCallback = function(event) {
      // Position C: this is now the newly instanciated object as it was bound at position B.
      console.log(this.someValue);
  };

  return theClass;
})();

var myObject = new MyClass();
myObject.initSomething(); 
deceze
  • 510,633
  • 85
  • 743
  • 889
peter_the_oak
  • 3,529
  • 3
  • 23
  • 37