How to use this keyword in JavaScript

Source: Internet
Author: User

In object-oriented programming language, we are very familiar with this keyword. For example, C ++, C #, and Java all provide this keyword. Although it is difficult to start learning, you only need to understand it, it is very convenient and meaningful to use. JavaScript also provides this keyword, but it is much more "messy" than the classic OO language.

Let's take a look at the confusion in the use of this in JavaScript?

1. Use the this keyword in the inline mode of HTML element event attributes:

<Div onclick ="
// You can use this

"> Division element </div>

A common method is to use the following format: audio cirpt: EventHandler (this. However, you can write any legal JavaScript statement here. If you are happy to define a class here, You can (but it will be an internal class ). The principle here is that the script engine generates an anonymous member method for the div instance object, and onclick points to this method.

2. Use the this keyword in the event processing function in DOM mode:

 Copy codeThe Code is as follows:
<Div id = "elmtDiv"> division element </div>
<Script language = "javascript">
Var div = document. getElementById ('mtdiv ');
Div. attachEvent ('onclick', EventHandler );

Function EventHandler ()
{
// Use this
}
</Script>

In this case, the this keyword in the EventHandler () method indicates that the object is the window object of IE. This is because EventHandler is just a common function. After attachEvent, the script engine calls it and the div object itself has no relationship. At the same time, you can look at the caller attribute of EventHandler, which is equal to null. If we want to obtain div object reference in this method, we should use: this. event. srcElement.

3. Use the this keyword in the event processing function in DHTML mode:

<Div id = "elmtDiv"> division element </div>
<Script language = "javascript">
Var div = document. getElementById ('mtdiv ');
Div. onclick = function ()
{
// Use this
};
</Script>

Here, the this keyword indicates the content of the div element object instance. In the script, the DHTML method is used to directly assign an EventHandler to div. onclick, which is equal to adding a member Method to the div object instance. The difference between this method and the first method is that the first method is the HTML method, while the DHTML method is used here. The latter script parsing engine will not generate an anonymous method.

4. Use the this keyword in the class definition:

 Copy codeThe Code is as follows:
Function JSClass ()
{
Var myName = 'jsclass ';
This. m_Name = 'jsclass ';
}

JSClass. prototype. ToString = function ()
{
Alert (myName + ',' + this. m_Name );
};

Var jc = new JSClass ();
Jc. ToString ();

This is the use of this in the JavaScript simulation class definition, which is very familiar with other OO languages. However, the member attributes and methods must be referenced using the this keyword. Running the above program will be notified that the myName is not defined.



5. Add the this keyword in the original method to the internal objects of the script engine:

Copy codeThe Code is as follows:
Function. prototype. GetName = function ()
{
Var fnName = this. toString ();
FnName = fnName. substr (0, fnName. indexOf ('('));
FnName = fnName. replace (/^ function /,'');
Return fnName. replace (/(^ \ s +) | (\ s + $)/g ,'');
}
Function foo (){}
Alert (foo. GetName ());

Here this refers to the instance of the class to be added, which is similar to the class definition in 4 and has nothing special.

6. Use this keyword in combination with 2 & 4:

 Copy codeThe Code is as follows:
Function JSClass ()
{
This. m_Text = 'division element ';
This. m_Element = document. createElement ('div ');
This. m_Element.innerHTML = this. m_Text;

This. m_Element.attachEvent ('onclick', this. ToString );
}

JSClass. prototype. Render = function ()
{
Document. body. appendChild (this. m_Element );
}

JSClass. prototype. ToString = function ()
{
Alert (this. m_Text );
};

Var jc = new JSClass ();
Jc. Render ();
Jc. ToString ();

Let me talk about the result. After the page is run, it will display: "division element". Click the text "division element", and it will display: "undefined ".

7. Use the this keyword in the expression of CSS:

 Copy codeThe Code is as follows:
<Table width = "100" height = "100">
<Tr>
<Td>
<Div style = "width: expression (this. parentElement. width );
Height: expression (this. parentElement. height); ">
Division element </div>
</Td>
</Tr>
</Table>

This can be viewed as the same as that in 1. It also refers to the div element object instance itself.

8. Use the this keyword in the internal function of the function:

 Copy codeThe Code is as follows:
Function OuterFoo ()
{
This. Name = 'outer name ';

Function InnerFoo ()
{
Var Name = 'inner name ';
Alert (Name + ',' + this. Name );
}
Return InnerFoo;
}
OuterFoo ()();

The running result is "Inner Name, Outer Name ". As described in section 2, if the result is "Inner Name, undefined", is it more reasonable? But the correct result is indeed the former, which is determined by the scope of JavaScript variables. For details, see the article "the keyword 'var 'in the original JScript is still an article" and reply.

After talking about the usage of this in so many JavaScript scripts, the most fundamental feature of this is consistent with the definition in the OO language. The reason why there are so many seemingly confusing usage methods is that the implementation of JavaScript language (the interpreter and the content of the language itself) follows OO (Object-based ), even if all its data types are objects, there is a super Object like an Object. However, this language does not follow the complete OO features when it is running (runtime), so it is confusing to refer to this.

Where can this be used in JavaScript? This is what I can think of for the time being. You are welcome to discuss it.

Related Article

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.