What is happening in the below 2 JavaScript statements? -
imgmonsterrun.onload = handleimageload; imgmonsterrun.onerror = handleimageerror; what handleimageload , handleimageerror?
are variables, or methods, or objects?
and if objects, method of object going run when object called upon?
some background
imgmonsterrun (we assume) image object. @ point, had src specified, points image loaded from. when specify src, browser starts loading image, lets move on rest of program.
however, programs might want things after image done loading, or perhaps if error occurs while image being loaded.
to that, use event handlers. "event" describes happening, such image being loaded or error occurring. event handler function gets called when event fires ("happens").
your code
one way attach event handler to, say, load event of image (imgmonsterrun example) using:
imgmonsterrun.onload = handleimageload; handleimageload expected function. instance, can define:
function handleimageload() { console.log("image loaded!"); } and log "image loaded!" when onload event fires (presumably when image imgmonsterrun done loading).
more detail
in javascript, functions first-class objects. means can passed around , dealt if "ordinary" objects.
so, when you're assigning handleimageload imgmonsterrun.onload, imgmonsterrun.onload() becomes equivalent handleimageload().
try it!
to grasp on concept, try stuff this:
function foo() { alert("hi! i'm foo."); } var bar = foo; // "reference" `foo` function assigned `bar`. // `bar` function, too. bar(); // alert "hi! i'm foo."
Comments
Post a Comment