【问题标题】:Javascript - Double callbacks from chrome extension not working with "this" [duplicate]Javascript - 来自 chrome 扩展的双重回调不适用于“this”[重复]
【发布时间】:2014-06-02 14:29:53
【问题描述】:

我已经构建了一个 Chrome 扩展来执行跨域 ajax 请求... 现在我试图将它包装到一个 javascript 面向对象的框架中。代码如下:

function webpage(url)
{
    this.url = url;
    this.html = "";
}

webpage.prototype.set_html = function(html)
{
    console.log(html); // working
    this.html = html; // not working
}

webpage.prototype.get_html = function()
{
    request_url(this.url, this.set_html); // call to a working chrome extension
}

var mypage = new webpage("http://www.google.it");
mypage.get_html();

问题是原型函数“set_html”如果我称它为“正常方式”,效果很好

mypage.set_html("hello world")

“request_url”函数也很好用

request_url("http://www.google.it",function(data){console.log(data)})

但是当我这样称呼它时

mypage.get_html();

第一个“console.log”效果很好,它显示了 page_source,但 this.html 的值不会改变......我错在哪里?

【问题讨论】:

    标签: javascript google-chrome object callback this


    【解决方案1】:

    这是重复的,因为类似的问题已经被问过很多次了。为了完整起见,我将参考 JavaScript 中的 this 来回答它。您的问题的一种解决方案可能是将 closure 传递给 request_url 而不是函数:

    webpage.prototype.get_html = function()
    {
      var me = this;
      request_url(this.url, function(){me.set_html(arguments);});
    }
    

    或者你可以使用bind:(对于像IE 8这样的旧浏览器可能需要一个polyfil)

    webpage.prototype.get_html = function()
    {
      request_url(this.url, this.set_html.bind(this));
    }
    

    更多关于构造函数和thishere的值(在this变量下)

    【讨论】:

    • 谢谢!这成功了!
    猜你喜欢
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 2018-03-12
    • 2021-09-24
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多