开发者

reference - event object attributes

Regarding the code below, how does the 开发者_如何学JAVAinterpreter know that event has attribute .keyCode. This code works, I just don't understand completely why, and more so were is this documented. How does it know what type of object event is. What if I would have called it 'e' or 'e1'. Where is the method prototype f1(Event) documented?

function b0(event) 
  {if (event.keyCode==13) 
    {i4(); 
    return false;}} 


function o5('f4b_',b0); 

o5(a,b){document.getElementById(a).onkeypress=b;}

where the element id a is an input text box.


The name of event is irrelevant, inside the function it's just another variable. You can rename it to JellyMan, and if you rename if (event.keyCode==13) to if (JellyMan.keyCode==13) it will work fine.

The type of event is determined by the script at run-time. The interpreter does not know that event has an attribute of .keyCode - if you tried to call it, and passed in a parameter that isn't the correct type: b0('wheee, break it'); then it will fail.

When the author wrote the script, he decided that function b0 would take one parameter (he called it event) and it would be a eventHandler - this doesn't get specified anywhere, it's just assumed that nobody's going to call it with something else. All eventHandlers have a .keyCode attribute, so it's therefore assumed that the object being passed in has one.


The interpreter doesn't have to "know". When the runtime system invokes an event handler, it passes it an object with more-or-less well-documented properties.

If you ran that code in a broken browser that passed in weird event objects, the code would fail.


Remember that javascript is interpreted code, not pre-compiled code. Any variable can hold any type.

So, in the function b0, the 2nd line of code:

if (event.keyCode==13)

says to the interpreter to get the first parameter passed to the function (named event) and fetch the attribute from it named keyCode. Javascript will look at the event parameter and see if it is the right type of variable to have an attribute and whether it actually has an attribute named keyCode. If it does, it will fetch it's value and compare it to 13. If it is not the right type of variable to have any attributes, then that line of code will fail and javascript will throw an exception. If it is the right type of variable to have an attribute, but does not have an attribute named keyCode then it will proceed with a value for that attribute of undefined which will fail the equality test with 13.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜