javascript--new understanding of the This pointer

Source: Internet
Author: User

All along, the understanding of this is only available, will be used, but not to delve into its essence.

This time, through "JavaScript The Good Parts", made a deep understanding.

Let's take a look at this one here.

When we declare a function, each function, in addition to the parameters (formal parameter) of the definition, will have an additional two parameters, one is this and the other is arguments (actual argument). Arguments is the argument that the function actually accepts, and is an array of classes. Arguments I only make a brief introduction, the emphasis we put on the this pointer.

In object-oriented, this is important, and its value depends on the mode of the call. In JavaScript, there are 4 call patterns: Method invocation mode, function call pattern, constructor call pattern, and apply invocation pattern.

    • Method invocation Pattern

When a function is a property of an object, we often call this function a method of this object. When this method is called, this points to the object to which the method belongs.

<script type= "Text/javascript" >    var people = {        "Yika",        function  () {            Console.log (this. name);   // "Yika"                        // This is already bound to the people object.         }    }    people.sayname (); </script>

As the chestnut shows, this points to the Sayname object, which is the public method of obtaining the context of the owning object through this. (Publice method)

    • Function call pattern

When a function is called not a method on an object, it is invoked as a function.

This mode call, this will point to the Window object, even though this function may be called in an external function, let's look at chestnuts.

1<script type= "Text/javascript" >2     varName = "Window-yika";3     varPeople = {4Name: "People-yika",5Student:function(){6Console.log ( This);//Here the This binding is the object people7             functionSayname () {8                 varName = "Sayname-yika";9Console.log ( This. name);//Window-yikaTen             //even though the Sayname function itself and its people object have a name value, this is a pointer to the window One             }; A sayname (); -         } -     } the  - people.student (); -</script>

In this way, it is not likely to know how to solve the JavaScript "design error".

Yes, only in the student function, which is line 6th, the this cache. You can then transfer this through the variable to the Sayname function to solve it!

varPeople ={name:"People-yika", Student:function(){             var = this ; // cache this.             functionSayname () {varName = "Sayname-yika"; Console.log (self.name);   //"People-yika", at which point the self is pointing to the People object            };        Sayname (); }    }
    • Constructor call pattern

In JavaScript, when it comes to constructors, it's in your mind: "The name of the function is capitalized!" Use the new operator when calling! The function name capitalization is understood to standardize the naming of unified constructors. But have you ever delved into why use new? If you call with new in front of a function, the function background creates a new object that points to the function prototype, and this also binds to the new object . JavaScript is a prototype based on the inheritance of the language, the prototype prototype is not very clear that students can check their own information, I focus on this.

Let's take a look at what the constructor usually looks like.

<script type= "Text/javascript" >functionpeople (name) { This. name = name;//this here, which is called after the new object Yika    
     this. Sayname = function () { Console.log (this. Name); // output } }
varYika =NewPeople ("Yika"); Yika.sayname (); //Output"Yika" because Yika is called through new and this is bound to the Yika object. </script>

At first glance, as if not understood, how is this in the function just point to the window, now without caching can point to the people function?

It doesn't matter, just said the function through new call, will secretly do "do bad things", we together to see what has done.

<script type= "Text/javascript" >functionpeople (name) { var that = {};   //bad one: Generate an Object yourselfThat.name =name; That.sayname=function() {console.log (that.name);        };  return that;    //bad two, you'll change the return behavior, return the object you just created    }    varYika =NewPeople ("Yika"); Yika.sayname (); //output "Yika" as it was just now .</script>

So you can see clearly that new will not only generate an object, but will also return the object automatically, so that this will point to this new object.

Remember to use new to call the constructor, or there is a problem, there is no warning, all uppercase conventions are very necessary.

    • Apply Call pattern

The Apply method lets us construct a parameter array to pass to the calling function, and also allows us to change the this value.

Function.apply (the value of this binding, arguments parameter array)

Apply can say too many things, I only give a chestnut here to help you understand:

<script type= "Text/javascript" >functionpeople (name) { This. Name =name;  This. Sayname =function() {Console.log ( This. name);//Sayname This method belongs to the people constructor.        }    }    functionStudent (name) {people.apply ( This, arguments);//The integration method of borrowing constructors is to invoke the people constructor via apply in the student constructor and change the people's This value                                      //this invokes the people constructor each time the student instance is created    }    varStudent =NewStudent ("Yika"); Student.sayname (); //output "Yika"</script>

We can easily modify the function by apply the this binding object, and apply a similar method call also has the same effect, interested students can search their own study.

Well, at the end of the four call patterns that change this, the method invocation pattern and the constructor invocation pattern are more and more important, and the function invocation pattern, we have to learn to avoid the pitfalls.

If there are errors, please reflect in time, I will correct as soon as possible to prevent misleading others, thank you!

javascript--new understanding of the This pointer

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.