1

I'm new to Javascript, so could anyone tell me why the value of 'this' changes depending on which function I'm calling it from. Am I not calling the addquote as a method (#3 from here? I mostly wrote this as an OOP exercise, so if anyone could point me in the way of good documentation that would be very much appreciated. Thanks!

function QuoteBox(text, author){
    this.quote = new Quote(text, author);
    this.element = document.getElementById("quotebox");
}


QuoteBox.prototype.removequote = function(c){
        // do some animation here and maybe move the removal to a callback
    this.element.children[0].innerHTML = "";
    this.element.children[1].innerHTML = "";
    c();
}

QuoteBox.prototype.addquote = function(){
    console.log(this); // outputs the window ?!
    this.element.children[0].innerHTML =quote.text;
    this.element.children[1].innerHTML =quote.author;
}

QuoteBox.prototype.refresh = function(){
    console.log(this); // outputs the quotebox object
    this.quote.generate();
    this.removequote(this.addquote);
}

$(document).ready(function() {
    quotebox = new QuoteBox("Quote", "Author");
    window.setInterval(function(){
        quotebox.refresh();
    }, 5000);
});
Community
  • 1
  • 1
  • Take a look at this question and its answers: http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal – Guilherme Sehn Nov 23 '13 at 04:04
  • Thanks for the references! Let me know if there's any point of stackoverflow etiquette I'm not following, I'm new here. – user3024029 Nov 23 '13 at 18:43

2 Answers2

0

Because you call c() in removequote function without specifying target object for this call. So, it shoud be c.call(this)

Good article about this topic - http://unschooled.org/2012/03/understanding-javascript-this/

Ivan Antropov
  • 414
  • 2
  • 14
0

When you call the function like this:

this.removequote(this.addquote); 

You're passing in the reference to the addquote into removequote, so your c holds a reference to the addquote method but not the context. When you call c(), this method will be invoked in global context. You can bind context to the method using bind. Like this:

this.removequote(this.addquote.bind(this));
Khanh TO
  • 46,783
  • 12
  • 97
  • 112