1

In the following Javascript code, the first call to saveResult from writeData succeeds while the second doesn't, please help.

class SimpleClass {

  constructor() {
    this.ir = "";
  }

  saveResult(res) {
    console.log("entered save result")
    this.ir = res;
    console.log("value saved is " + this.ir);
    console.log("end save result");
  }

  writeData() {
    this.saveResult("abc"); //works fine

    var sr = this.saveResult;
    sr("abc"); //throws error -> Cannot set property 'ir' of undefined
  }
} //end of class

function testLocally() {
  var sc = new SimpleClass();
  var wr = sc.writeData();
  console.log("done");
}

testLocally();
Ele
  • 33,468
  • 7
  • 37
  • 75
Ankit Jain
  • 119
  • 6
  • You're losing the lexical scoping when you're setting the function to a variable. – Ele Feb 17 '19 at 13:06
  • Where is this.saveResult in the constructor btw? – Rafv Feb 17 '19 at 13:07
  • 1
    If you do this `sr.bind(this)("abc")` will work because you're setting the context to the function. – Ele Feb 17 '19 at 13:09
  • Thanks Ele, I understood that I was missing the context and that can be passed either through the way you suggested or as described in the answer below using `sr.call(this, "abc");` – Ankit Jain Feb 17 '19 at 13:48

1 Answers1

1

A function gets is context based on how it is invoked. When you call it like

this.saveResult("abc"), this inside the function will refer to the this which called it, which in your case is the class context since you created an instance of class and invoked writeData method from the class instance causing the this inside writeData to refer to class context.

However when you run it like this:

var sr = this.saveResult;
sr("abc"); 

Although sr has the reference to the function, its called from the window context and hence it doesn't work correctly. You can call it using .call method and provide the context like this:

var sr = this.saveResult;
sr.call(this, "abc");
letsintegreat
  • 3,328
  • 4
  • 18
  • 39
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 1
    Dupe question!! – Ele Feb 17 '19 at 13:15
  • Hi Ele Thanks for linking the 2 questions but that question starts from the root cause which is the same for these 2 questions. I think this question will be a very useful example to anyone who is trying to understand the issue described in the other question, so unless someone knows the reason behind the problem already it is difficult to find out the reason with the help of other question alone. So I think this question should not be marked as a duplicate of the other question just because the root cause is the same. – Ankit Jain Feb 17 '19 at 13:43