This in JavaScript

Source: Internet
Author: User

This in JavaScript is always confusing and should be one of the well-known pitfalls of js. I personally think this in js is not a good design. Due to the late binding feature of this, it can be a global object, the current object, or... Some people even use this because of a big pitfall.


In fact, if you fully grasp the working principle of this, you will naturally not go into these pitfalls. Let's take a look at what this points to in the following situations:

1. In the global code, this
1 alert (x );
// The value of global variable x is 2.

 


This within the global range will point to the global object, even if the window is in the browser.

2. Simple function call
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
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

1 new FooCoder ();

This inside the function points to the newly created object.


5. Internal functions
Var name = "clever coder ";

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

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

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

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:

When a function is called as an object's method, this points to this object.
When a function is called as a fade-out function, this points to the Global Object (undefined in strict mode)
In the constructor, this points to the newly created object.
This in nested functions does not inherit this of upper-level functions. If needed, 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 ,...);

 

Further steps

We may often write such code:

1 $ ("# 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.

1 arg1, arg2 ,...

When a binding function is called, these parameters plus the bound function parameters will be used as the original function runtime parameters in order.


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.
1
2 $ ("# 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:
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 )));
};
};

 

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.