简体   繁体   English

将'this'范围传递给回调函数

[英]Passing 'this' scope to callback function

I'm trying to pass 'this' to a callback function. 我正在尝试将“ this”传递给回调函数。 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? 如何以最佳方式实现自己想要的?

Use bind then: 然后使用bind

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

Use bind , as mentioned by Bhojendra Nepal. 使用bind ,如Bhojendra Nepal所述。

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

do_this(callback.bind(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM