A couple of things are going on here:
In this code:
setTimeout(this.hide_member(this.memb), 2000);
you're calling this.hide_member
immediately, and passing its return value into setTimeout
. This is exactly like foo(bar())
, where you're calling bar
and passing its return value into foo
.
You need to pass a function into setTimeout
, and then call the member function from within that function. Note that within the function, this
will be different, so you have to remember it:
a.prototype.show_member = function(){
var self = this,
memb_to_hide = this.memb;
setTimeout(function() {
self.hide_member(memb_to_hide);
}, 2000);
this.memb++;
}
Note that I also remembered the old value of this.memb
to use in the function.
Another way to do that is with ES5's Function#bind
, but it requires that the browser's JavaScript engine have that (or that you've loaded an "ES5 shim", as bind
is a shimmable feature):
a.prototype.show_member = function(){
setTimeout(this.hide_member.bind(this, this.memb), 2000);
this.memb++;
}
Function#bind
returns a function that, when called, will call the original function using the value you give in the first argument as this
(and then passing on any further arguments). In this case, we didn't have to remember the old value of this.memb
because we've already passed the old value into bind
.
Side note: You're relying on the horror that is Automatic Semicolon Insertion. I recommend not doing that, and supplying semicolons at the ends of your statements, e.g.:
a.prototype.mumble = function() {
/*...*/
}; // <=== Note the ;