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?
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?
Share Improve this question edited Feb 3, 2015 at 14:07 casraf asked Feb 3, 2015 at 14:01 casrafcasraf 21.7k10 gold badges60 silver badges93 bronze badges 1-
1
}).bind(this));
will bind the scope of the function without executing it immediately. – pawel Commented Feb 3, 2015 at 14:03
2 Answers
Reset to default 10Use bind then:
do_this((function() {
returh this.test + 5;
}.bind(this));
Use bind, as mentioned by Bhojendra Nepal.
function callback() {
return this.test + 5;
}
do_this(callback.bind(this));