New Understanding of this pointer in JavaScript, javascriptthis

Source: Internet
Author: User

New Understanding of this pointer in JavaScript, javascriptthis

For a long time, the understanding of this is only available and can be used, but does not go deep into its essence. This time, I made a deep understanding through JavaScript The Good Parts. (ALL debugging tasks can be viewed on the console, with the F12 key in the browser)

Let's take a look at this.

When we declare a function, each function has two additional parameters besides the parameters parameter in definition. One is this and the other is arguments ). Arguments is the parameter actually accepted by the function and is an array of classes. Arguments I will only give a brief introduction, focusing on the this pointer.

This is very important in object orientation. Its value depends on the call mode. In JavaScript, there are 4 call modes: method call mode, function call mode, constructor call mode, and apply call mode.

Method call mode

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

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var people = {
Name: "Yika ",
SayName: function (){
Console. log (this. name); // "Yika"
// This is already bound to the people object.
}
}
People. sayName ();
</Script>

As shown in the chestnut, this points to the sayName object. this method of obtaining the context of the object through this is a public method. (Publice method)

Function call mode

When a function is called, instead of a method on an object, it is called as a function.

In this mode, this will point to the window object, even if this function is called in an external function, let's look at it.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var name = "window-Yika ";
Var people = {
Name: "people-Yika ",
Student: function (){
Console. log (this); // here this is bound to the object people
Function sayName (){
Var name = "sayName-Yika ";
Console. log (this. name); // window-Yika
// Even if the sayName function itself and its people object both have the name value, this indicates
};
SayName ();
}
}

People. student ();
</Script>

In this case, do you probably know how to solve the "design error" of JavaScript.

Yes, you only need to cache this in the student function, that is, the 6th rows. Then, you can transfer this to the sayName function through the variable!

Copy codeThe Code is as follows:
Var people = {
Name: "people-Yika ",
Student: function (){
Var self = this; // cache this
Function sayName (){
Var name = "sayName-Yika ";
Console. log (self. name); // "people-Yika", at this time, self points to the people object
};
SayName ();
}
}

Constructor call mode

When it comes to constructors in JavaScript, my mind will be: "function name writing! The new operator is used for calling !" To standardize and unify the name of the constructor, write a good understanding of the function name. But have you ever wondered why new is used? If a function is called with new in front of it, a new object pointing to the prototype of the function will be created in the function background, and this will also be bound to the new object. JavaScript is a language based on prototype inheritance. If you are not clear about prototype, you can check the information yourself. I will focus on this.

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

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function People (name ){
This. name = name; // this indicates the new object Yika.
This. sayName = function (){
Console. log (this. name); // output
}
}
Var Yika = new People ("Yika ");
Yika. sayName (); // output "Yika", because Yika is called through new, and this is bound to the Yika object.
</Script>

At first glance, it seems that it is not easy to understand. Why does this point in the function just point to the window? Can this point to the People function without caching?

It doesn't matter. I didn't just say that a function is called through new. Will it "Do bad things" by itself in the background? Let's take a look at what has been done.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function People (name ){
Var that = {}; // bad thing 1: generate an object by yourself
That. name = name;
That. sayName = function (){
Console. log (that. name );
};
Return that; // Second, the system will change the return action, and the newly generated object will be returned.
}
Var Yika = People ("Yika"); // new can be omitted here, imitating the call of the new operator
Yika. sayName (); // output "Yika" just like"
</Script>

In this case, we can see clearly that new not only generates an object, but also automatically returns this object. this naturally points to this new object.

Remember to use new to call the constructor. Otherwise, there is no warning, and all the upper-case conventions are necessary.

Apply call mode

The apply method allows us to construct a parameter array and pass it to the call function. It also allows us to change the value of this.

Function. apply (this bound value, arguments parameter array)

There are too many things that can be said by apply. Here I will just give you a chestnut to help you understand:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function People (name ){
This. name = name;
This. sayName = function (){
Console. log (this. name); // The sayName method belongs to the People constructor.
}
}
Function Student (name ){
People. apply (this, arguments); // borrow the constructor integration method. In the Student constructor, call the People constructor through apply and change the this value of People.
// In this way, the People constructor is called every time a Student instance is created.
}
Var student = new Student ("Yika ");
Student. sayName (); // output "Yika"
</Script>

We can easily modify the this bound object of the function through apply, and the call method similar to apply has the same effect. If you are interested, you can search and learn it by yourself.

Now, we have finished talking about the four call modes for changing this. The method call mode and the constructor call mode will use more and more importantly. The function call mode, we must learn to avoid the traps.

If there are any errors, please reflect them in time and I will correct them as soon as possible to avoid misleading others. Thank you!

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.