Drongo_III Posted May 18, 2014 Share Posted May 18, 2014 (edited) Hi Guys I wonder if someone can explain something that is probably quite basic. When I try to add an event listener and target a normal function this works fine - e.g. 'window.addEventListener('load',test)'. However, if I try to target a function that is a property of an object this fails - e.g. 'window.addEventListener('load',initialiser.init)'. Further in this latter case I also get a console log saying it's undefined. The code for this example is below. So my question is why does it fail onload when I use a function in an object as opposed to a straight function? Presumably it's something to do with the way the document and the code are loaded or initialised but what is it that makes them behave differently. Thanks, Drongo <script> //this function call works fine //window.addEventListener('load',test); //this functiton call fails and is undefined in console window.addEventListener('load',initialiser.init); //example object holding a method var initialiser = { init:function(){ alert('Init called!'); } }; //some random function function test(){ alert('test called!'); } </script> Edited May 18, 2014 by Drongo_III Quote Link to comment https://forums.phpfreaks.com/topic/288579-onload-object-method-vs-function/ Share on other sites More sharing options...
Solution Drongo_III Posted May 18, 2014 Author Solution Share Posted May 18, 2014 (edited) Little more research has uncovered the answer. Apparently function declarations are loaded into the execution context before anything else. Whereas a function expression is evaluated only when the parser reaches it. Hope that helps anyone else confused by this quandary. Edited May 18, 2014 by Drongo_III Quote Link to comment https://forums.phpfreaks.com/topic/288579-onload-object-method-vs-function/#findComment-1479944 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.