The simple understanding of this point in JavaScript

Source: Internet
Author: User

  the first thing to say is that thepoint 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, this ultimately points to the object that called it ( there are some problems, which will explain why there is a problem, although most of the online articles are said, although in many cases to understand that there is 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 certainly know what to do with, if you have not learned, then temporarily can not read this article, of course, if you are interested can also see, after all, this is JS must master the Things.

Example 1:

function a () {    var user = "little j";    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 user = "little j";
Console.log (this//undefined console.log (this);

Window

The same as the above code, in fact, the alert is also a window of a 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 carried out by O.fn (), that natural point is the object o, here again, the point is that the pointer to the function when the creation of the decision is not, in the call to decide, who calls the point to who, 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// dream child}} Window.o.fn ();

This code and the above code is almost the same, but here is why this is not pointing to the window, if according to the above theory, the end of this point is to call its object, here first to say a digression, window is the global object in js, The variable we created actually adds a property to the window, so you 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 the object above, then this point is the window, it is necessary 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 yourself.
================================================>>>>>

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 a function has this, the function contains multiple objects, Although the function is called by the outermost object, this point is only the object of its upper level , example 3 can prove that if you do not believe, So let's look at a couple of examples Next.

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 always points to the last object to invoke it , that is, to see who called it when it executes, example 4, although the function fn is referenced by the object b, but 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 the FN.

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

Constructor version of This:

function Fn () {    this. user = "little j";}  var New  //little J

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, because the new keyword is to create an object instance , Understand this sentence can think about our example 3, we use variable A to create an instance of FN (the equivalent of copying a copy of FN into object a), at this time just create, and not execute, and call this function fn is Object a, then this point is the nature of object a, So why is there a user in the object fn because you have copied an FN function into object a, and the New keyword is the same as copying one copy.

In addition to the above, we can also change this point to ========>>> call , apply, bind

Update a small problem when this hit return

function fn ()  {      This. user = ' little J ';        return  {};  } var New fn;   // undefined

Look at one more

function fn ()  {      This. user = ' little J ';        return function (){};} var New fn;   // undefined

Again

 function   fn () { this . user = ' Little J '  return  1;}  var  a = new    fn; Console.log (a.user);  //little J   
function fn ()  {      This. user = ' little J ';        return undefined;} var New fn;   //little J

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. user = ' little J ';        return undefined;} var New fn;   // fn {user: "little j"}

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. user = ' little J ';        return NULL ;} var New fn;   //little J

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 () {    this. num = 1;}  var New  //1

Why does this point to a? First the New keyword creates an empty object, and then it automatically calls a function apply method, which points to the empty object, so that the inside of the function is replaced by this empty object.

The simple understanding of this point in JavaScript

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.