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?

ComFreek
  • 27,416
  • 16
  • 97
  • 150
  • 1
    possible duplicate of [What does var that = this; mean in javascript?](http://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript) –  May 17 '14 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. – ComFreek May 17 '14 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. –  May 17 '14 at 12:11

1 Answers1

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) );
ComFreek
  • 27,416
  • 16
  • 97
  • 150
  • Interesting: I was wondering how to pass this and I (poor me) tried to pass it as a function argument :-) –  May 17 '14 at 12:03
  • 1
    @3000 Actually, you don't need any callback function. You can also use `chrome.alarms.onAlarm.addListener(this.f2.bind(this));` – ComFreek May 17 '14 at 12:06