2

I'm trying to pass 'this' to a callback function. I know a "suitable" way of doing this is setting this to a variable and using the variable... but that's not very elegant.

var that = this;
chrome.storage.sync.set(this.defaultOptions, function () {
    that.loadOptions();
});

I'm trying something else, but I can't figure out how to do it. Here's what I have tried:

chrome.storage.sync.set(this.defaultOptions, (function () {
    this.loadOptions();
}).call(this));

But it's not working out. I'm getting this error:

Error in response to storage.set: Error: Invocation of form 
get(object, undefined) doesn't match definition 
get(optional string or array or object keys, function callback)

Other questions on SO I've tried looking into have similar needs but not quite the same. How can I achieve what I want in the best way?

casraf
  • 21,085
  • 9
  • 56
  • 91
  • 1
    `}).bind(this));` will bind the scope of the function without executing it immediately. – pawel Feb 03 '15 at 14:03

2 Answers2

9

Use bind then:

do_this((function() {
    returh this.test + 5;
}.bind(this));
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • I've updated the question to the exact code, and namely I'm (still) getting this error: `Error in response to storage.set: Error: Invocation of form get(object, undefined) doesn't match definition get(optional string or array or object keys, function callback)` (though I have to admit my IDE likes `bind`) – casraf Feb 03 '15 at 14:09
  • I did in my tests, I just didn't put bind in the question to avoid confusion. Both with call and bind I still get this error – casraf Feb 03 '15 at 14:11
  • Put the bind method in your question, so that I could see if there's any problem...may be you're using bind method wrongly... – Bhojendra Rauniyar Feb 03 '15 at 14:11
  • My bad, this fixed it, the error was repeating in another place that did the same, I updated that and it worked. Thanks! I'll accept the answer when I'm allowed – casraf Feb 03 '15 at 14:13
0

Use bind, as mentioned by Bhojendra Nepal.

function callback() {
  return this.test + 5;
}

do_this(callback.bind(this));
Ezequias Dinella
  • 1,278
  • 9
  • 12