I explained how to use this in JavaScript to a friend two days ago. I said that I should pay attention to the context of this, but I cannot understand it. Alas, I don't blame him. This in Javascript is sometimes very worrying, and even those of us who often write will occasionally be faint. Later, I was forced to write a smallProgramIt was finally explained clearly. Oh, my God! The whole person is in a mood to be released. I believe I can fly...
I simply put the example here and added a detailed comment. It should be said that this example is the most basic application embodiment of this role change. The right should be an entry. Senior players do not need to watch it. They skipped it directly.
1 Function Clickfun (value, domele ){
2 // Save the value passed in by the parameter in the current Object Property _ value
3 This . _ Value = Value;
4
5 // Save the reference to the DOM element in the current Object Property _ domele.
6 This . _ Domele = Document. getelementbyid (domele );
7
8 // This. _ domele has become a reference to Dom components.
9 // The following pure this indicates the current object clickfun.
10 // Therefore, this equivalent means: Dom element. buttonfun attribute = Object clickfun
11 This . _ Domele. buttonfun = This ;
12
13 This . _ Domele. onclick = This . Clickhandler;
14
15 };
16 Clickfun. Prototype. clickhandler = Function (){
17 // The magic is coming! Here, note that you have to push the topic.
18 // First go back to the constructor. Condition 1: Dom element. buttonfun property = Object clickfun
19 // NextCode, Condition 2: This references the DOM element! (Good Time)
20 // The code below also looks at, Condition 3: This (DOM element). The buttonfun property is registered to the variable buttonobj
21 // In conclusion, it is inferred that the variable buttonobj is referenced by the object clickfun!
22 VaR Buttonobj = This . Buttonfun;
23
24 // What will happen next is no suspense t_t
25 VaR Value = (Buttonobj && Buttonobj. _ value) ? Buttonobj. _ value: " Unknown Value " ;
26 Alert ( " Value: " + Value );
27 // Remember, here this cursor is already a DOM element.
28 Alert ( " This. value: " + This . Value );
29 };
30
31
32 Window. onload = Function (){
33 New Clickfun ( " Value assigned to the program " , " BT " );
34 }
The HTML code is as follows:
1 < Button Type = "Button" Value = "I am the value of the button" ID = "BT" > Click me </ Button >
Test button:Click me