Usage of this object in JavaScript

Source: Internet
Author: User

In js, there are many ways to use this. The following describes the common usage of this in js, anyone who needs to know how to use this will not be able to refer to it.

Let's take a look at what this points to in the following situations:

1. In the global code, this:

1 alert (this) // window <
This within the global range will point to the global object, even if the window is in the browser.

The Code is as follows: Copy code
Function fooCoder (x ){
This. x = x;
}
FooCoder (2 );

Alert (x); // the value of global variable x is 2

Here this points to the global object, that is, window. In strict mode, it is undefined.

3. method call as an object:

The Code is as follows: Copy code

Var name = "clever coder ";
Var person = {
Name: "foocoder ",
Hello: function (something ){
Console. log (this. name + "says" + something );
}
}
Person. hello ("hello world ");

Output foocoder says hello world. This indicates the person object, that is, the current object.

4. As a constructor:

The Code is as follows: Copy code

New FooCoder ();

This inside the function points to the newly created object.

5. Internal functions:

The Code is as follows: Copy code

Var name = "clever coder ";
Var person = {
Name: "foocoder ",
Hello: function (something ){
Var sayhello = function (something ){
Console. log (this. name + "says" + something );
};
Sayhello (something );
}
}
Person. hello ("hello world"); // clever coder says hello world


In internal functions, this is not bound to the outer function object as expected, but to the global object. This is generally considered a JavaScript design error because no one wants to point this in internal functions to a global object. The general processing method is to save this as a variable, which is generally agreed to be that or self:

The Code is as follows: Copy code

Var name = "clever coder ";
Var person = {
Name: "foocoder ",
Hello: function (something ){
Var that = this;
Var sayhello = function (something ){
Console. log (that. name + "says" + something );
};
Sayhello (something );
}
}
Person. hello ("hello world"); // foocoder says hello world


6. Use call and apply to set this:

The Code is as follows: Copy code


Person. hello. call (person, "world ");

The apply and call operations are similar, but the following parameters are passed in through an array instead of separately. Method definition:

 

The Code is as follows: Copy code

Call (thisArg [, arg1, arg2 ,... ]); // Parameter list, arg1, arg2 ,...

Apply (thisArg [, argArray]); // parameter array, argArray

Both are used to bind a function to a specific object. Naturally, this is explicitly set as the first parameter.

Summary
Simply summing up the above points, we can find that only the sixth point is confusing.
In fact, we can summarize the following points:
1. When a function is called as an object's method, this points to this object.
2. When a function is called as a fade-out function, this points to a global object (undefined in strict mode)
3. this In the constructor points to the newly created object.
4. this in nested functions does not inherit this of upper-level functions. If necessary, you can use a variable to save this of upper-level functions.
To sum up the simplicity, if this is used in a function, this will point to this object only when the function is directly called by an object.

Obj. foocoder ();

Foocoder. call (obj ,...);

Foocoder. apply (obj ,...);

We may often write such code:

The Code is as follows: Copy code


$ ("# Some-ele"). click = obj. handler;

If this is used in handler, will this be bound to obj? Obviously not. After a value is assigned, the function is executed in the callback. this will be bound to the $ ("# some-div") element. This requires understanding the execution environment of the function. This article does not describe the execution environment of functions in length. You can refer to the introduction of the execution environment and scope chain in javascript advanced programming. This is a better understanding of the execution environment of js functions.
So how can we solve the problem of callback function binding? ES5 introduces a new method, bind ():

Fun. bind (thisArg [, arg1 [, arg2 [,...])

ThisArg
When the binding function is called, this parameter points to this when the original function is running. When the new operator is used to call the binding function, this parameter is invalid.
Arg1, arg2 ,...
When a binding function is called, these parameters plus the bound function parameters are used as the parameters for the original function runtime in sequence. <

 

This method creates a new function called the binding function. The binding function uses the first parameter of the bind method as this when it is created, the second and later parameters passed in the bind method plus the parameters bound to the function runtime are used as parameters of the original function in order to call the original function.
Obviously, the bind method can solve the above problems well.

The Code is as follows: Copy code
$ ("# Some-ele"). click (person. hello. bind (person ));

// When the corresponding element is clicked, the output foocoder says hello world


In fact, this method is easy to simulate. Let's look at the source code of the bind method in Prototype. js:

The Code is as follows: Copy code

Function. prototype. bind = function (){
Var fn = this, args = Array. prototype. slice. call (arguments), object = args. shift ();
Return function (){
Return fn. apply (object,
Args. concat (Array. prototype. slice. call (arguments )));
};
};

I have read another article to summarize.

In JavaScript, what is the confusion about how to use this?

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

The Code is as follows: Copy code

<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:

The Code is as follows: Copy code

<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:

The Code is as follows: Copy code
<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:

 

The Code is as follows: Copy code

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:

The Code is as follows: Copy code
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:

The Code is as follows: Copy code

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:

The Code is as follows: Copy code
<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:

The Code is as follows: Copy code

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.

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.