Accessing ‘this’ inside a JavaScript callback function

Feedback

Question:

During the Callback, I attempt to utilize a function present in the
extended class
.

Model.findOne( { _id: id }, function( err, rec ){
    super.handleFind( err, rec ); 
});

Upon compiling my Typescript, an error is displayed as follows:

error TS2660: 'super' can only be referenced in members of derived classes or object literal expressions.

Upon executing the JavaScript, the output received is:

TypeError: Cannot read property 'call' of undefined

Before the Callback, assigning `super.handleFind` to `fct` appears functional, however, `this` is not defined within `handleFind()` which is necessary for the contextual reference.


Solution 1:

If

handleFile

is defined in the parent class, it will be passed down to your subclass. However, if you are overriding

handleFile

in your subclass and prefer to utilize the superclass’s

handleFile

implementation, you can simply invoke it using

this.handleFile

.

The second problem arises from passing a callback with

function() {...}

to

Model.findOne

. To maintain the

this

context and make it point to your subclass’s current instance, switch to using an arrow function. Therefore, modify your function as follows.

 // Use arrow function to make 'this' point to the current instance of the
 // enclosing class
Model.findOne( { _id: id }, ( err, rec ) => {
    super.handleFind( err, rec ); 
});


Solution 2:


Invoke the anonymous function passed to

.findOne()

with

this

context using

Function.prototype.call()

. This can be accomplished with

Model

and

class

.

class Test {
  constructor() {}
  handleFind(err, rec) {
    console.log(err, rec)
  }
}

class Model extends Test {
  constructor() {
    super()
  }
  findOne(id, fn) {
    fn.call(this, id, "err")
  }
}

var model = new Model();

model.findOne({id: 123}, function(err, rec) {
  this.handleFind(err, rec)
});

Frequently Asked Questions