Jump to content

onLoad - object method vs function

Go to solution Solved by Drongo_III,

Recommended Posts

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.





       //this function call works fine

       //this functiton call fails and is undefined in console
	//example object holding a method
	var initialiser = {
			alert('Init called!');

	//some random function
	function test(){
		alert('test called!');
Edited by Drongo_III
Link to comment
Share on other sites

  • Solution

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 by Drongo_III
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.