1

I have a problem with Javascript forcing the [object DOMWindow] into an function I have in an object's prototype. The full error I get is below:

Uncaught TypeError: Object [object DOMWindow] has no method 'positionconvert'

Basically what I'm doing is inside the object prototype under certain conditions I'm creating a var interval that counts off with window.setInterval():

var interval = window.setInterval(this.alertanimate, 500);

the alertanimate function is inside the same prototype, and uses the this variable in this line:

this.positionconvert(this.alerticon, -69, 55);

(positionconvert is yet another function, and alerticon is an object). The problem is when I get window.setInterval involved js starts assuming this is the DOM and not the object prototype, like I intended, presenting the above error. When I hard-code this to work with a specific object it works, but somewhere in this variable-passing the this variable loses its connection to the object. I hope this all makes sense? What am I doing wrong?

Artur Sapek
  • 2,425
  • 6
  • 27
  • 29
  • possible duplicate of [setTimeout and "this" in JavaScript](http://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript) – Felix Kling Aug 10 '11 at 07:59

2 Answers2

3

Passing this.alertanimate to setIntervall loses the connection to the main object. What this refers to in a function is entirely defined by how the function is called. If you pass a function to setTimeout then this will refer to window.

You can do:

var self = this;

window.setInterval(function() {
    self.alertanimate();
}, 500);

In newer browsers, you can also use .bind() [MDN] (see docs for an alternative implementation):

window.setInterval(this.alertanimate.bind(this), 500);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Oh my god that did it. I had tried the `var me = this;` trick and passing `me` into `alertanimate(me);` like that, but you have it right! Thanks! – Artur Sapek Aug 10 '11 at 08:00
1

Welcome to JavaScript. The this is re-bound every time you introduce a function scope.


    var outer = function() {
      var that = this;
      // that and this refer to the same object: outer
      var inner = function() {
        // now that refers to outer and this refers to inner
        ...
      }
      // that and this again refer to the same object: outer
      ...
    }

You didn't post your full code, but I suspect one of your inner this's doesn't mean what you think it does.

AustinDahl
  • 832
  • 7
  • 9
  • Ahh that's a good illustration. Yeah I didn't think my full code was necessary to communicate the problem, but this is a good way of explaining it. Thanks. – Artur Sapek Aug 10 '11 at 08:16