Passing 'this' scope to callback function

折月煮酒 提交于 2019-12-08 08:08:17

问题


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?


回答1:


Use bind then:

do_this((function() {
    returh this.test + 5;
}.bind(this));



回答2:


Use bind, as mentioned by Bhojendra Nepal.

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

do_this(callback.bind(this));


来源:https://stackoverflow.com/questions/28300796/passing-this-scope-to-callback-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!