Exploring the basic knowledge of this pointer in JavaScript

Source: Internet
Author: User
Because JavaScript is bound at runtime, this in JavaScript can be a global object, current object, or any object, depending entirely on the function call method. Explore the point of this pointer in JavaScript

First of all, it must be said that the point of this cannot be determined when the function is defined. Only when the function is executed can we determine who the point of this is, in fact, this ultimately points to the object that calls it (this sentence has some problems and will be explained later why, although most articles on the Internet say this, although in many cases it will not be a problem to understand it in that way, but in fact it is not accurate to understand it in that way, so you will have a hard-to-understand feeling when you understand this ), then I will discuss this issue in depth.

Why learning this? If you have learned functional programming and object-oriented programming, you must know what to do. If you have not learned it, you do not need to read this article for the time being, of course, if you are interested, you can also take a look. After all, this is something that must be mastered in js.

Example 1:

Function a () {var user = "dream catcher"; console. log (this. user); // undefined console. log (this); // Window} ();

According to the above-mentioned this, the final point is to the object that calls it. Here function a is actually vertex by the Window object, and the following code can prove it.

Function a () {var user = "dream catcher"; console. log (this. user); // undefined console. log (this); // Window} window. a ();

Like the code above, alert is actually an attribute of window, which is also generated by window.

Example 2:

Var o = {user: "dream catcher", fn: function () {console. log (this. user); // dream catcher} o. fn ();

Here this points to the object o, because you call this fn through o. if fn () is executed, it naturally points to the object o. Here again, this point cannot be determined when the function is created, and can be determined only when the function is called, you must be clear about who calls it.

In fact, Examples 1 and 2 are not accurate enough. The following example can overturn the above theory.

To thoroughly understand this, you must refer to the following examples.

Example 3:

Var o = {user: "dream catcher", fn: function () {console. log (this. user); // dream catcher} window. o. fn ();

This code is almost the same as the above Code, but why does this not point to the window? Based on the above theory, this eventually points to the object that calls it, here, let's talk about window as a Global Object in js. The variable we created is actually adding properties to window, so here we can use window point o object.

Here, I will not explain why the above Code, this, does not point to the window. Let's look at a piece of code.

var o = {  a:10,  b:{    a:12,    fn:function(){      console.log(this.a); //12    }  }}o.b.fn();

This is also the o point of the object, but this does not execute it, then you will certainly say that what I said at the beginning is not all wrong? Actually, it's not. It's just an inaccurate description at the beginning. Next I will add a sentence. I believe you can fully understand the problems that this points.

Scenario 1: If a function contains this, but it is not called by an object at the upper level, this points to window, here, we need to note that in the strict version of js, this is not a window, but we will not discuss the strict version issue here. If you want to know, you can search for it on the Internet.

Case 2: If a function contains this and this function is called by an object at the upper level, this points to the object at the upper level.

Case 3: If a function contains this, this function contains multiple objects. Although this function is called by the outermost layer object, this points to only the objects at the upper level, example 3 proves that, if you do not believe it, we will continue to look at several examples.

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

Although object B does not have attribute a, this point is also object B, because this will only point to its upper-level object, no matter whether the object has anything this requires.

There is also a special case, Example 4:

var o = {  a:10,  b:{    a:12,    fn:function(){      console.log(this.a); //undefined      console.log(this); //window    }  }}var j = o.b.fn;j();

Here this points to the window, isn't it a bit blind? In fact, it is because you do not understand a sentence that is equally important.

This always points to the object that finally calls it, that is, who calls it during execution. In example 4, although the fn function is referenced by object B, however, when fn is assigned to variable j, It is not executed, so the final point is window. This is different from example 3. Example 3 directly executes fn.

This is actually the same thing, but in different cases, it may point to something different. In the summary above, there are some small errors in each place, and it cannot be said to be wrong, however, it may be different in different environments, so I can't explain it clearly at a time. You can only understand it slowly.

Constructor version this:

Function Fn () {this. user = "dream catcher";} var a = new Fn (); console. log (a. user); // dream catcher

Here, object a can point out the user in function Fn because the new Keyword can change the point of this and point this to object a. Why do I say "a" is an object, because the new keyword is used to create an object instance. To understand this sentence, consider example 3, here we use variable a to create an Fn instance (equivalent to copying a Fn to object a). At this time, we only create the instance and do not execute it, however, if the Fn function is called by object a, this is actually directed to object a. Why is there a user in object Fn, because you have copied a Fn function to object a, using the new keyword is equivalent to copying a function.

In addition to the above, we can also change the point of this on our own. For details about how to change the point of this on our own, refer to the summary of the call, apply, and bind methods in JavaScript, it details how to manually change the point of this.

Update a small problem when this encounters return

Function fn () {this. user = 'dream catcher '; return {};} var a = new fn; console. log (a. user); // undefined

Let's look at another one.

Function fn () {this. user = 'dream catcher '; return function () {};} var a = new fn; console. log (a. user); // undefined

Come back

Function fn () {this. user = 'dream catcher '; return 1;} var a = new fn; console. log (. user); // dream catcher function fn () {this. user = 'dream catcher '; return undefined;} var a = new fn; console. log (. user); // dream catcher

What does it mean?

If the returned value is an object, this points to the returned object. If the returned value is not an object, this still points to the function instance.

Function fn () {this. user = 'dream catcher '; return undefined;} var a = new fn; console. log (a); // fn {user: "dream catcher "}

Another point is that although null is also an object, here this still points to the function instance, because null is special.

Function fn () {this. user = 'dream catcher '; return null;} var a = new fn; console. log (a. user); // dream catcher

Knowledge Point supplement:

1. In the strict version, the default this is not a window, but undefined.

2. The new operator will change the point-to-point of the function "this". Although we have explained it above, we have not discussed it in depth, and we seldom talk about it on the Internet. So it is necessary to talk about it here.

function fn(){  this.num = 1;}var a = new fn();console.log(a.num); //1

Why does this point to? First, the new keyword will create an empty object, and then a function apply method will be automatically called to point this to this empty object, in this way, this inside the function will be replaced by this empty object.

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.