javascript - Why is a more convoluted jQuery pattern necessary here? -
javascript - Why is a more convoluted jQuery pattern necessary here? -
to me, next code seems reasonable enough:
$("#onebutton").click( alert("hello"); );
it seems when onebutton clicked, please pop alert saying "hello".
however, in reality, alert pops regardless of whether button clicked or not.
one has wrap alert("hello");
in anonymous function, , (and then), alert popping depend on clicking button. me seems unnecessarily convoluted.
there must reason why designers of jquery thought acceptable alert in code above pop when button hasn't been clicked. reason?
fair question guess, although i'm not fan of arrogance came :)
lets break downwards bit:
object.method(function() { alert('hi'); });
your question is, why can't skip anonymous function?
what we're doing here, telling method
execute @ later point. what's beingness executed beingness supplied function.
we give reference function instead!
object.method(alert);
here's problem, we've sent function, can't send arguments. if want bring arument along method
, must utilize (
, )
.
as characters included, alert
instead executed , result of alert
sent method
.
now why can't sent reference? simple reason, need some way pass result of function argument function, , javascript engine cannot distinguish if intent to:
send result of function argument other function, or send reference function arguments other function.using (
, )
on function means calling in every programming language, , javascript no different.
there workaround:
object.method(alert.bind(this, "hi"));
javascript
Comments
Post a Comment