Jump to content

onLoad - object method vs function


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.

 

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>
Link to comment
https://forums.phpfreaks.com/topic/288579-onload-object-method-vs-function/
Share on other sites

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. 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.