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 [obje开发者_运维知识库ct 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?
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);
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.
精彩评论