0

When I call one function, "this" contains all the the "stuff", but when I call a function that calls another functions, "this" returns undefined inside the second function.

Code:

class test {
  test() {
    console.log(this) // => returns class functions ect..
    this.run(this.test2);
  }
  run(func){
      func()
  }
  test2() {
    console.log(this) // => returns undefined
    this.function3(); // => ERROR
  }

  function3() {
    console.log("hey")
  }
}

var t = new test();

t.test();

Why does the code behave this way? and how do I resolve this issue

Sam H
  • 401
  • 2
  • 5
  • 12

2 Answers2

2

Ah, those are colled closures. The context (this) will be different, depending on from wich context the function will be called. For javascript a function is an object and it's binding to a class object is week. It can be detached from the class and used separately with on problem. That's why when you call this.someFunc() it gives you only a function, but not the function of this actual instance. The most common way to bypass it is to save an object context to a separate variable and use in istead of this. Something like that:

class test {
  var self = this;
  test() {
    console.log(self)
    this.run(self.test2);
  }
  run(func){
      func();
  }
  test2() {
    console.log(self);
    self.function3();
  }

  function3() {
    console.log("hey");
  }
}
1

When the function passed into run is executed, it's this is pointing to a new execution context, not the instance of the class that you are expecting.

This can be 'solved' by binding its execution context to the instance of the class, either when passed to run, e.g.

this.run(this.test2.bind(this))

Or I'm the constructor, e.g.

constructor () {
  this.test2 = this.test2.bind(this)
}
Jake
  • 179
  • 1
  • 4