In JavaScript, the this pointer points to a thorough understanding

Source: Internet
Author: User

The first thing to say is that the point of this is not deterministic at the time of the function definition, and only when the function is executed can you determine who this is pointing to,
In fact the end point of this is the object that called it (there are some problems in this sentence, which will explain why there is a problem,
Although most of the articles on the internet say so, although in many cases to understand that there will be no problem, but in fact, that understanding is inaccurate,
So you have a elusive feeling when you understand this, then I'll delve into the problem.

Why do you want to learn this? If you have learned functional programming, object-oriented programming, then you must know what to do with it, if you have not learned it,
So temporarily do not have to read this article, of course, if you are interested can also see, after all, this is the JS must master the things.

Example 1:

function A () {    var" chasing the Dream";    Console.log (this//undefined    console.log ( this// Window }a ();

As we said above, this finally points to the object that called it, where function A is actually being ordered by the Window object, and the following code can prove it.

function A () {    var" chasing the Dream";    Console.log (this//undefined    console.log (this); // Window }window.a ();

The same as the above code, in fact, the alert is also a window property, but also window points out.

Example 2:

var o = {    User:" chasing the dream ",    fn:function () {        Console.log (  this. user);  // chasing the dream son     }}o.fn ();

Here the this point is the object o, because you call this FN is executed through O.FN (), that natural point is the object o, here again to emphasize a little,
The point of this can not be determined when the function is created, it is only possible to decide when the call is made and who is to be called, so be sure to figure this out.
In fact, example 1 and Example 2 are not accurate enough, the following example can overturn the above theory.
If you want to understand this thoroughly, you have to look at the next few examples

Example 3:

var o = {     User:" chasing the dream ",     fn:function ()    {        Console.log (this//    }}window.o.fn ();

This code is almost the same as the code above, but here's why this is not pointing to window, if you follow the above theory,
The end of this point is to call its object, here to say a digression, window is the global object in JS, we create the variable is actually to add properties to the window, so here can use the window point O object.
Here's why the above code does not point to window, so let's look at a piece of code.

var o = {    A:ten,    b:{        A:        fn:function () {            Console.log (this//    )}}o.b.fn ();

Here is also the object o point out, but the same this does not execute it, then you will certainly say that I started to say that those are not all wrong?
In fact, is not, just at the beginning of the inaccurate, I will add a word, I believe you can thoroughly understand this point of the problem.

Case 1: If there is this in a function, but it is not called by an object of the previous level, then this is the window,
Here is to explain that in the strict version of JS this point is not the window, but we do not discuss the strict version of the problem, you want to know that you can search the Internet.
Scenario 2: If a function has this, the function is called by the object above, then this is the object at the top level.
Case 3: If there is this in a function, the function contains multiple objects, although the function is called by the outermost object, this is only the object of its upper level.
Example 3 can prove that if you do not believe, then we continue to look at a few examples.

var o = {    A:ten,    b:{        //  a:12,        fn: function () {            Console.log(this//undefined        }    }}o.b.fn () ;

Although there is no attribute a in object B, this is also object B, because this only points to its upper-level object, regardless of whether there is anything in this object.
There is a more special case, example 4:

var o = {    A:ten,    b:{        A:        fn:function () {            Console.log (this//undefined            console.log (this//  window        }    }}var j = o.b.fn;j ();

Here this is pointing to window, is it some kind of blindfold? It's just as important that you don't understand a word.
This is always the last object to call it, that is, to see who is calling when it executes, in Example 4, although the function fn is referenced by object B,
However, when the FN is assigned to the variable j is not executed, so the final point is the window, which is not the same as the example 3, example 3 is the direct execution of FN.

This said to go in fact is that one thing, but in different circumstances point to a little different, the above summary of each place have some small mistakes,
Can not be said to be wrong, but in different circumstances will be different, so I have no way to explain clearly, only you slowly to realize.

Constructor version of this:

function Fn () {    this" chasing the dream ";} var New  // Chase dream Son

The reason why object A can point out the function fn inside the user is because the New keyword can change the point of this, the this point to object A, why I say A is an object,
Since the use of the new keyword is to create an object instance, to understand this sentence can think of our example 3, we here with the variable A to create an instance of FN (the equivalent of copying a copy of the FN into object a),
At this point just create, and do not execute, and call this function fn is object A, then this point is the natural object A, then why the object FN will have the user,
Because you have copied an FN function into object A, using the New keyword is equivalent to copying a copy.

In addition to the above, we can also change the direction of this, about the point of changing this to see the summary of the Call,apply,bind method in JavaScript, this article,
Detailed instructions on how we can manually change the point of this.

Update a small problem when this hit return

function fn ()  {      this' chasing the dream son ';       return  {};  } var New fn;   // undefined

Look at one more

function fn ()  {      this' chasing the dream son ';       return function () {};} var New fn;   // undefined

Again

function fn () { This. user ='chasing the dream son'; return 1;}varA =Newfn; Console.log (A.user); //chasing the dream sonfunction fn () { This. user ='chasing the dream son'; returnundefined;}varA =Newfn; Console.log (A.user); //chasing the dream son

What do you mean?
If the return value is an object, then this is the object that is returned, and if the return value is not an object then this is an instance of the function.

function fn ()  {      this' chasing the dream son ';       return undefined;} var New fn;   // fn {User: "Chasing the Dream"}

Another point is that although Null is also an object, here this is an instance of the function, because NULL is special.

function fn ()  {      this' chasing the dream son ';       return NULL ;} var New fn;   // chasing the dream son

Knowledge Point Supplement:
1. The default this in the strict edition is no longer the window, but the undefined.
The 2.new operator will change the point of the function this, although we have explained above, but not in-depth discussion of this issue, the Internet is rarely said, so it is necessary to say here.

function fn () {    this1;} var New  //1

Why does this point to a? First the New keyword creates an empty object and then automatically calls a function apply method, which points to the empty object,
In this case, the inside of the function will be replaced by this empty object.

In JavaScript, the this pointer points to a thorough understanding

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.