This in javascript is used for event registration and event

Source: Internet
Author: User

 

This article does not discuss the differences between the syntax interpretation period and the execution period, as well as the concept of the Context Environment and closure. We can only look at the problem from another perspective.

In js, this is a pointer that refers to an object. In general, remember one principle:

 

If a function is not used as a class to instantiate an object such as new func ();

However, when a function is called as a method of an object, this points to the object;

If this function is directly called, this points to the global variable...

This sentence does not seem to be easy to understand. Let's look at the example:

Function test (){

This. name = 'franky ';

}

Var o = {};

O. t = test;

O. t (); // here the test method is called as the method t of object o. then the internal this points to the object o. this. name = 'franky 'is equivalent to o. name = 'franky'

Alert (o. name); // print franky

However, if we call the test () method directly, this points to the global variable because it is not called as a method of an object, but directly called.

Now we can directly access the attribute name of the global variable Through alert (window. name); or alert (name.

 

Now let's take a look at event registration

There are three methods for event registration

1. Hard encoding: Write event registration directly in html element. For example:

<Div id = "div1" onclick = "alert (this. id)"> test </div>

2. Traditional Methods in js blocks are as follows:

Document. getElementById ('did1'). onclick = function () {alert (this. id );}

3. Use attachEvent and addEventListener to register events.

The classic one here is the addEvent method encapsulated by the Jquery author. Although there are many shortcomings, I will explain it later.

 

Now, let's take a look at the hard encoding format.

<Div id = "div1" onclick = "alert (this. id)"> test </div>

Why does this point to the div1 element?

The answer is. hard-coded event registration. The browser will encapsulate your code into an (anonymous) function.

Now we can take a look at it by printing the onclick attribute of div1.

Alert (document. getElementById ('did1'). onclick) // note that this is not onclick ()

We will see that ie has printed the function anonymous () {} // you will know the name. It is called an anonymous function.

Opera print function (event) {}// well. This is a standard anonymous function.

Safari chrome ff print function click (event) {}// here, the three browsers give the function a corresponding event name.

 

Here, we can see what the browser will do when the div1 click event occurs? Yes, he will try to execute div1.onclick () // if he is a method now

The general process is if (div1.onclick) div1.onclick (); so now the packaging function is called by the browser as the method of the div1 element object, and the internal point of this is div1.

Then it is clear that the document. getElementById ('div1 ') = function () {alert (this. id)} In the hardcoded and js Blocks )}

So we can even directly execute this method rather than trigger it through an event. That is, div1.onclick (); // directly execute it ..

However, we should note that manual calling of this method will not generate browser events. It will only execute alert (this. id); this sentence.

So let's look at the process of triggering browser events?

If you carefully read the hardcoded onclick, it is not difficult to find the w3c browser's packaging function, no matter what it is called, but it always has a form parameter called event.

Yes. this is the event object. Therefore, in the hard-coding environment, we can not only directly use this to reference the current element, but also directly use event to reference the event object.

In addition, this write method is compatible with all browsers. The reason is that the w3c packaging function has a type parameter called event and ie? Window. event can be abbreviated as event. The current event object is also obtained ....

The w3c browser will pass a parameter in the event-triggered callback function, but ie will not

Therefore, we can obtain parameters in non-hard encoding mode.

Obj. onclick = function (e ){

E = e | window. event; // w3c browser e indicates that the object is used for logical operations, that is, true, even if (new Boolen (false) // true

// In ie, because the event object will not be passed in, e = undefined. Then e = window. event

}

Okay. this is why hard-coded registration events that we used a long time ago can be directly compatible with all browsers. in fact, this is because various browsers are paying tribute to ie .... wrap the function parameter named event ..

But you must never think that e = e is not required in js blocks if we call event. | window. event

For example:

Obj. onclick = function (event ){

Event // remember that this is different from hard encoding. Here, the event is still undefiend in ie. This is caused by the scope. event is a local variable at this time. Please think about it for specific reasons.

}

So there is only one last hard encoding. In the hard encoding environment, we can omit this. For example:

<Div id = "div1" onclick = "alert (this. id)"> test </div>

It is equivalent

<Div id = "div1" onclick = "alert (id)"> test </div>

Each browser supports this write because the local variable is first found in the Attribute Table of element. and then global. but I do not recommend this. hard encoding is not even recommended. the reason is understandable.

 

Now that the topic of today is this, let's talk about the two special cases of this.

1. call and applay

Yes, the two methods are used to modify the object pointed to by this pointer. the only difference between them is the method of passing parameters. for more information, see the manual. this is no longer a long time. check the Code:

Function test (){

This. name = 'franky ';

}

Var o = {};

Var o2 = {};

O. t = test;

O. t (); // at this time, o. name = 'franky ';

However

O. t. call (o2); // execute this sentence only. name = 'undefined' o2.name = 'franky '. yes, call forces this in method t to point to o2.

This is the role of call and applay. In js inheritance, you may see code similar to the following:

Function ClassA (){

This. name = 'franky ';

}

Function ClassB (){

ClassA. call (this); // when you execute ClassA, you only execute ClassA as a common function. the difference is that the reference of this in the ClassA method is modified through call. point it to the ClassB instance.

}

At this time, we

Var obj = new ClassB ();

Instantiate a ClassB and create a copy, that is, object obj. What we need to know is that. ClassB () and new ClassB () will lead to the execution of ClassB. Even if we write var obj = new ClassB;

According to js rules. in this case, this in ClassB will; point to obj, then its internal ClassA. call (this); equivalent to ClassA. call (obj); that is, this in ClassA is changed by call to point to obj

In ClassA, this. name = 'franky 'is equivalent to obj. name = 'franky'; // this achieves inheritance of dynamic attributes and methods.

If we really understand this, we should understand why this inheritance method cannot inherit the attributes and methods of the ClassA prototype. Instead, we can only inherit dynamic attributes and methods.

Let's see what new has done.

Function NEW (Class) {// The new Class of the shanzhai version is the constructor to be instantiated ..

Var obj = {};

Obj. _ proto __= Class. prototype;

// The _ proto _ attribute is invisible to ie. You can test in ff that binding is required before calling.

// So why can we use if (this instanceof arguments. callee) in the constructor to determine whether the constructor is called using new.

// Of course, this judgment method is not 100%. If the constructor is called as its instance method, the above conditions are the same. However, this requirement is basically impossible.

Var returnValue = Class. call (obj );

If (typeof returnvalue = 'object' & returnvalue! = NULL) return returnvalue;

Return OBJ;

}

 

 

With the wide application of Ajax, we have to mention a very special thing:

This in the onreadystatechange method of the xhr object in IE does not point to xhr.

This is very different from the theoretical system we have learned.

VaR xhr = new XMLHttpRequest;

Xhr. onreadystatechange = function () {This // This in IE unfortunately does not point to xhr}

However, IE7 does not know if it is because it supports the local XMLHttpRequest instead of ActiveX. It seems to solve this problem, but for compatibility.

So we need to do this.

Xhr. onreadystatechange = function () {handler. Call (xhr );}

Function handler (){......}

Okay. Here we can basically figure out this...

If you want to thoroughly understand how the relationship between this is maintained, you can take a look at the Javascript authoritative guide. this reference has a more underlying description. you can see how JS maintains this relationship through prototype chain.

 

Ps: It seems that the writing will be confiscated. The more you write, the more you have to briefly describe about event registration. The addEvent written by the jquery author and its shortcomings are as follows:

1. Memory leakage

2. The error message returned when duplicate registration is ignored in attachEvent.

3. the execution order of several methods for registering the same event of the same object is the opposite.

4. because it fixes the this reference issue. however, a new problem occurs. when the same prototype method of multiple instances of the same constructor registers to the same event of the same element, _ this points to the last instantiated object.

The above problems 1 and 4 are the new problems caused by this reference, and 2 and 3 are inherent problems of attachEvent.

The addEventListener is perfect without any problems.

Dean Edwards wrote two versions of addEvent a few years ago. You can go to his blog to see it. Although there are still some problems, it also has advantages.

He gave up attachEvent and addEventListener, and used the traditional method to flexibly register and delete event registration with guid.

. All the headaches come from the attachEvent of ie. So I ended this chapter with the help of what I often say: IE SUCKS !!!

 

Source: http://www.cnblogs.com/_franky/archive/2009/03/23/1420029.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.