将“this"作用域传递给回调函数 [英] Passing 'this' scope to callback function

查看:53
本文介绍了将“this"作用域传递给回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将this"传递给回调函数.我知道这样做的合适"方法是将其设置为变量并使用该变量......但这不是很优雅.

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)

关于 SO 我尝试调查的其他问题有类似的需求,但不完全相同.我怎样才能以最好的方式实现我想要的?

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?

推荐答案

使用 绑定 然后:

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

这篇关于将“this"作用域传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆