When the div is clicked, the pop-up box displays undefined.
The reason is that when a DOM object responds to a click event, the This keyword in the event method points to a DOM object, and the DOM object does not have a property, so it pops up the undefined.
And the programmer is meant to respond to this in the event method this point is ClassA object A, how can this be achieved? This requires that you use the call or Apply method.
code is as follows |
copy code |
<title>apply_and_call</title> <body onload= "init ()" > <div id= "Testdiv" style= position:absolute; border:1px soli D Gray; width:100px; height:100px "></div> <script type=" text/javascript "> function init () { var el = document.ge Telementbyid ("Testdiv"); var a = new ClassA (EL); } Function ClassA (EL) { THIS.A = 1; This.container = El; //Bind order hit event This.container.onclick = This.click; } Classa.prototype = { Click:function () { alert (THIS.A); } </script> </body> |
Let's familiarize yourself with the call method below:
Summary:
Function.call (thisobj, args ...)
Parameters:
Thisobj
The object that invokes the function. In the body of a function, Thisobj is the value of this keyword.
Args ...
Any number of parameters that are passed to function functions.
return value:
Invokes the return value of the function functions.
Thrown:
TypeError
If the object that calls the function is not a function, the exception is thrown.
Describe:
Call () invokes the specified function functions as Object thisobj, passing the thisobj argument in the argument list to it, and the return value is the return value after the function is invoked. In the function body, the keyword this refers to the Thisobj object.
Use the Function.apply () method if the specified array is used as a parameter passed to the function.
After you are familiar with the call () method, modify code 1 as follows
The code is as follows |
Copy Code |
<title>apply_and_call</title> <body onload= "init ()" & Gt <div id= "Testdiv" style= "Position:absolute; border:1px solid Gray; width:100px; height:100px" ></div> br> <script type= "text/javascript" > function init () { var el = document.getElementById ("Testdiv"); var a = new ClassA (EL); } Function ClassA (EL) { this.t = 1; This.clickdele = Createdele (This.click, this); El.onclick = This.clickdele; } Classa.prototype = { Click:function () { alert (THIS.T); } } Function Createdele (fun, obj, arg) { return function () { return fun.call (obj, arg); } </script> </body> |