Delve into the ubiquitous this in JS

Source: Internet
Author: User

Gold Code:

The This object is bound at run time based on the execution environment of the function: in the global function, this equals window and when the function is called as a method of an object, this is equal to that object.

Here are some related practices:

this<--------------------------------------------related to-------------------------------------------------> closures ------------

We know that the execution environment for anonymous functions is global, so this object usually points to window, but because closures are written differently, this may not be obvious:

What is this for? In fact, when each function is called, its active object will automatically get two special variables: this and arguments. When the intrinsic function searches for these two variables, it only searches for its active object, so it is never possible to directly access the two variables in the external function.

But the following rewrite, you can do it.

-----------------------------------------------> Functions related to this<---------------------------------------------- -------

Let's look at one of the most simple examples:

This will of course be undefined, because the point of this is actually a call to it.

Here are two special cases in which the performance of this in closures is:

Because the closure is executed immediately, which is equivalent to the function of the global role in the downward use, so, as you can see, he pointed to the window.

But ... in strict mode:

This is the sequela of using strict mode in closures, which does not point this to the global scope.

Here is a summary of the "use strict" in JavaScript, summed up pretty well understand:

So the this is pointing to his call, exactly how it points to it, let's try a few small examples to see how it behaves:

1. The most common:

See, just undefined, call this to point to the scope of the call it Oh.

This more confirms that this point is called to the scope of his call.

2. So I'm going to try to nest the functions for a moment:

Or window, here This is the window, it seems to say that it is not clear, write your own try to think, experience oh.

3. This is basically the case when the function is called, so let's try the function reference below to see what it looks like, slightly more complicated:

It turns out that a reference function can change the execution scope of a function, but as before, the calling function does not change the scope of the function's execution:

It turns out that the bar function does not change the execution scope of the function (note the me in the previous two pieces of code: How to use it later).

this<--------------------------------------------in------------------------------------------------> Constructors --------

1. Let's take a look at JS in the simple package process used in this:

The above implementation is not a strict encapsulation, but from which we can see the role of this.

2. Don't worry, there must be something interesting about it:

This creates a new object through new and passes this object through this to the constructor, which is why the scope of B runs to a{}.

What is this for?? Let's take a look at the new constructor: What's the use of this?

In simple terms:

In fact, the function of new is to make this point to a new object and return this.

The actual operation of the case is this:

1 function person () {2     //var obj = new Object (), 3     //this = obj;4     alert (this);     New Person Object 5     

In fact, the implementation of JS is this:

1 function newoperator (constr, args) {2     var thisvalue = object.create (Constr.prototype);//(1) 3     var result = Cons Tr.apply (Thisvalue, args); 4     if (typeof result = = = ' object ' && result!== null) {5         return result;//(2) 6     }7     return thisvalue;8}

Look at the information on the Internet when you see, Link here: Http://

---------------------------------------------the impact of >call and apply on this <--------------------------------------- ---------------------

See Example:

Here This will point to the string.

The above example, by call (), uploads x, y, to the function.

this<--------------in-------------------------------------------------------> Timers (settimeout,setinterval) ------------------------------------------------

First look at the simplest:

This is a pointer to window.

In fact, because settimeout () and SetInterval () are released at the window, of course, they point to window.

More evidence of what has been said above.

But in fact, setTimeout () will produce a non-conforming this. It runs in a separate execution context. As a result, he will point the This keyword to the window. There is a detailed explanation on the MDN:

1 MyArray = ["Zero", "one", "both"];2 Myarray.mymethod = function (sproperty) {3 alert (arguments.length > 0 This[sproperty]: this);4 };5 6 Myarray.mymethod (); //Prints "zero,one,two" 7 Myarray.mymethod (1); //Prints "one" 8 setTimeout (Myarray.mymethod, 1000); //Prints "[Object Window]" after 1 second 9 setTimeout (Myarray.mymethod, 1500, "1"); //prints "undefined" after 1.5 seconds Ten / Let's try to pass the ' this ' object One (MyArray, Myarray.mymethod, 2000); //Error: "Ns_error_xpc_bad_op_on_wn_proto:illegal operation on Wrappednative prototype object" (MyArray, Myarray.mymethod, 2500, 2);//Same error

But the MDN also provides a workaround:

1 MyArray = ["Zero", "one", "both"];2 Myarray.mymethod = function (sproperty) {3 alert (arguments.length > 0 This[sproperty]: this);4 };5 6 setTimeout (Alert, and "Hello world!"); //The standard use of setTimeout and setinterval are preserved, but  ...7 (MyArray, Myarray.mymethod, 2000); //Prints "Zero,one,two" after 2 seconds (MyArray, Myarray.mymethod, 2500, 2);//Prints "both" after 2.5 seconds

The this<------------------------------------------------------------------------------------------>eval () ------------------------------------------------

Call Eval directly ():

If you call eval () directly, this points to the current scope. (' Use strict ' is not the same)

The following shows the situation where the call is not straightforward:

this<-------------------------------------in-------------------------------------------------------> complex situations -------------------

In the process of finding information, found a summary of very good, complex case of this priority, affixed to the collection:

Priority level Scene The value of this Note
1 New New out of the empty object
Apply/call Parameters passed in Tie, Apply/call can't appear with new.
New ("1"); Error
2 Timer Window
3 Event The element in which the event occurred
4 Method Owner
5 Others (nested, etc.) window | | Undefined See if it's a strict mode

Note: No matter how you modify this,this, it only affects one layer


Delve into the ubiquitous this in JS

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