JavaScript scope issue with this.connection
I have the below JavaScript code. In the function update, the this.connection
resolves to undefined instead of a number. What am I doing wrong?
function Net()
{
this.connection = -1;
this.counter = 1;
this.timelastse开发者_StackOverflow中文版nd = -1;
setInterval( this.update, 3000);
}
Net.prototype.update = function()
{
if (this.connection > 0 && this.timelastsend > 0)
{
var now = new Date().valueOf();
if (now - this.timelastsend > 1000 * 60)
{
}
}
}
One of the problems of using this
is that this
is dependent on the way you call the function.
setInterval
will call your update
method as if it were a standalone function, and so this
will be set to the global object.
If you really need to use the this
functionality, rewrite your call to to setInterval as follows:
function Net() {
var self = this;
this.connection = -1;
this.counter = 1;
this.timelastsend = -1;
setInterval( function () { self.update() }, 3000);
}
This way, you’ll create a self
variable which will keep referring to your object (if you’ve created it using the new
operator — another reason to avoid this
).
Addendum: If you’re not actively descending lots of objects from your Net pseudoclass, I’d refactor the thing as follows:
function createNet() {
var connection = -1,
counter = -1,
timelastsent = -1,
self,
update;
update = function () {
var now;
if (connection > 0 && timelastsent > 0) {
now = new Date().valueOf();
if (now - timelastsent > 1000 * 60) {
// ... update code ...
counter += 1;
timelastsent = now;
}
}
};
setInterval(update, 3000);
return {
update: update,
getTimeLastSent: function () { return timelastsent; },
getCounter: function () { return counter; },
getConnection: function () { return connection; }
};
}
You’ll notice there is no mention of this
anywhere, which means no ambiguity. I’ve included three getters for the connection, counter and timelastsent properties, but if you want those to be writable from outside the object, you could just as easily add them to the created object.
精彩评论