0

I have a JS module:

var myModule = {

   f1 : function(){...},

   f2 : function(){...},

   f3 : function(){

   // this works
   this.f2();

   var objRef = this;

   chrome.alarms.onAlarm.addListener(function(){

          // this works
          objRef.f2();

          // this doesn't work
          this.f2();

   }

When, from the body of the listener block inside f3 I call f2 using this, I can't call it, probably because of a scope issue.

Question: is there any way to avoid the objRef solution to reference f2 function from the body of the listener?

3
  • 1
    possible duplicate of What does var that = this; mean in javascript? Commented May 17, 2014 at 12:01
  • 1
    @delnan I don't think so. The question and its answers you referenced discuss the usage of var that/self = this. It seems that the OP in this question already knows about the concept, but tries to find a cleaner way. Commented May 17, 2014 at 12:10
  • @ComFreek OP doesn't seem to be aware of it. But yes, that other question doesn't address how to get rid of objRef. Retracted. Commented May 17, 2014 at 12:11

1 Answer 1

2

Try Function.prototype.bind():

chrome.alarms.onAlarm.addListener((function(){

  // this works
  objRef.f2();

  // this will now work!
  this.f2();

}).bind(this));

Easier and cleaner approach (– if the call of f2 is the only statement which shall be executed):

chrome.alarms.onAlarm.addListener( this.f2.bind(this) );
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting: I was wondering how to pass this and I (poor me) tried to pass it as a function argument :-)
@3000 Actually, you don't need any callback function. You can also use chrome.alarms.onAlarm.addListener(this.f2.bind(this));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.