1

I've builded a Chrome extension to do cross-domain ajax requests... Now I'm trying to wrap it into a javascript object oriented framework. Here is the code:

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();

The problem is that the prototype function "set_html" is working great if I call it "the normal way"

mypage.set_html("hello world")

The function "request_url" is working great too

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

However when I call it like this

mypage.get_html();

The first "console.log" works great and it shows the page_source but the value of this.html won't change... Where I'm wrong?

Marco Moschettini
  • 1,555
  • 2
  • 16
  • 26

1 Answers1

1

It is a duplicate as similar questions about this have been asked many times. For completeness I'll answer it with a reference to what this is in JavaScript. One solution to your problem could be to pass a closure to request_url instead of the function:

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

Or you can use bind: (may need a polyfil for older browsers like IE 8)

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

More on constructor functions and the value of this here (under The this variable)

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160