I was wondering if someone could give me a simple solution to this.
I want to have the two dog instances repeat the bark + wag tail combination.
If all logic is contained within the barkNameAndTime function, I’m fine, but by calling wagTail via the setTimout I lose context. I don’t write much JS so my closure knowledge is a litle rust and I can’t quite seem to find a clean solutions.
Problem is that Baloo ends up doing all the barking and tail wagging and Lola is lost in the crowd 🙂
Thanks
Warrick
<script type="text/javascript">
$(document).ready(function () {
var zDog1 = new dog("Lola");
var zDog2 = new dog("Baloo");
zDog1.bark();
zDog2.bark();
});
function dog(aName) {
var name = aName,
barkNameAndTime = function () {
var time = new Date().getTime();
$('#MyDiv').html($('#MyDiv').html() + "<br />" + name + " barked @ " + time);
setTimeout(wagTail, 1000);
};
wagTail = function () {
var time = new Date().getTime();
$('#MyDiv').html($('#MyDiv').html() + "<br />" + name + " wagged tail @ " + time);
setTimeout(barkNameAndTime, 1000);
}
return {
bark: barkNameAndTime
};
}
In your implementation,
wagTailis a global variable (probably by mistake) so its one global value and context gets replaced each time you create a new dog object.If you make it a local variable (by changing one semicolon to a comma), it should work.
When it’s a local variable, then each copy of
wagTailkeeps its own closure context (and thus access to the local variables in its same stack frame). When it’s a global variable, all calls towagTailwill have the same context which will be the context the last time it was assigned to.FYI, this is one of the reasons I don’t like this way of declaring local variables when there are multiline initializers as one subtle typo renders some of them implicit global variables. I’d rather predeclare the locals and then assign to them in the body. Much less likely to suffer this error. Or, in this case, you don’t need to use the variable syntax, you could have just declared
barkNameAndTimeandwagTailas local functions (code example added by Bergi):