TheCrock Posted November 16, 2020 Share Posted November 16, 2020 I am following the excellent book Foundation Game Design with HTML5 and Javascript. I have a piece of code, which works but i'm not sure why. function destroyAlien(alien) { //Change the alien's state and update the object alien.state = alien.EXPLODED; alien.update(); //Remove the alien after 1 second setTimeout(removeAlien, 1000); function removeAlien() { removeObject(alien, aliens); removeObject(alien, sprites); } As you can see it is a function which uses setTimout to call another function. It only calls removeAlien function when it is inside the main function. If I move callAlien function out of the main function it does not work. I am puzzled as to why this is. Can any sage member here tell me why this is? Thanks in advance Crock TheCrock Posts: 2 Joined: 12 Nov 2020, 16:02 Quote Link to comment Share on other sites More sharing options...
b10b Posted November 19, 2020 Share Posted November 19, 2020 Javascript "scope". When running in "strict" mode a function can only access members of itself. To access functions or variables outside of itself involves other approaches. Perhaps "Foundation Game Design" covers this topic? https://www.w3schools.com/js/js_scope.asp Quote Link to comment Share on other sites More sharing options...
TheCrock Posted November 20, 2020 Author Share Posted November 20, 2020 Now I understand b10b Thank you for the reply and explanation with link.Most kind. Very early in the book there was indeed a paragraph on scope which I had forgotten. I ran a search for scope through the pdf and found it. Thanks again. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.