最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing 'this' scope to callback function - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 10

Use 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));
发布评论

评论列表(0)

  1. 暂无评论