New understanding of this pointer in JavaScript sharing _javascript tips

Source: Internet
Author: User
Tags function prototype

All along, the understanding of this is only available, it can be used, but it does not delve into its essence. This time, through the "JavaScript The Good Parts", made a profound understanding. (All debugging can be seen in the console, browser F12 key)

Let's take a look at this here.

When we declare a function, each function, in addition to the parameters (formal parameters) defined, will have an additional two arguments, one is this, and one is the arguments (argument). Arguments is the argument that the function actually receives and is an array of classes. Arguments I'll just make a brief introduction and focus on the this pointer.

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

Method invocation Pattern

When a function is a property of an object, 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 Code code 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 the chestnut shows, this points to the Sayname object, which is the method of obtaining the context of the owning object, which is the public method. (Publice method)

Function call pattern

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

This mode call, this points to the Window object, even though it might be called in an external function, we look at chestnuts.

Copy Code code as follows:

<script type= "Text/javascript" >
var name = "Window-yika";
var people = {
Name: "People-yika",
Student:function () {
Console.log (this); Here the This is bound to object people
function Sayname () {
var name = "Sayname-yika";
Console.log (this.name); Window-yika
Even though the Sayname function itself and its people object have a name value, this is a pointer to window's
};
Sayname ();
}
}

People.student ();
</script>

In this view, is not probably know how to solve JavaScript this "design error".

Yes, as long as in the student function, that is, line 6th, cache this. And then transfer this through the variable to the Sayname function can be solved!

Copy Code code as follows:

var people = {
Name: "People-yika",
Student:function () {
var self = this; To cache this
function Sayname () {
var name = "Sayname-yika";
Console.log (Self.name); "People-yika", at which point self is pointing to the People object
};
Sayname ();
}
}

Constructor call pattern

When you talk about a constructor in JavaScript, you'll have the following: "Function name caps!" Use the new operator when you call! The name of the function is well understood to standardize the naming of unified constructors. But have you ever delved into why you should use new? If called with new on the front of a function, the function background creates a new object that points to the function prototype, and this is also bound to the new object. JavaScript is a prototype based language, not very clear to the prototype prototype students can check the data, I focus on this.

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

Copy Code code as follows:

<script type= "Text/javascript" >
function people (name) {
THIS.name = name; Here's this, with the new call, and then points to the object Yika
This.sayname = function () {
Console.log (this.name); Output
}
}
var Yika = new People ("Yika");
Yika.sayname (); The output is "Yika" because the Yika is derived from the new call, which is bound to the Yika object.
</script>

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

It doesn't matter, just now is not to say the function is called by new, will secretly do "do bad things", we together to see what has been done.

Copy Code code as follows:

<script type= "Text/javascript" >
function people (name) {
var that = {}; Bad one: Generate an object of your own
That.name = name;
That.sayname = function () {
Console.log (That.name);
};
return to that; Bad two, you will change the return behavior, return just generated the object
}
var Yika = people ("Yika"); Here you can omit new and mimic the call to the new operator.
Yika.sayname (); Output "Yika" like just now.
</script>

This makes it clear that new will not only generate an object, but will also automatically return the object, so nature this points to the new object.

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

Apply Call Mode

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 (This binding's value, arguments parameter array)

There are so many things to apply that I can only raise a chestnut to help you understand:

Copy Code code as follows:

<script type= "Text/javascript" >
function people (name) {
THIS.name = name;
This.sayname = function () {
Console.log (this.name); Sayname This method belongs to the people constructor.
}
}
function Student (name) {
People.apply (this, arguments);//Borrow the constructor's integration way, in the student constructor, invoke the people constructor via apply, and change the people's This value
This will call the people constructor each time the student instance is created
}
var student = new Student ("Yika");
Student.sayname (); Output "Yika"
</script>

We can easily modify the function of this binding object, and apply similar methods call also has the same effect, interested students can search their own learning.

All right, that's it. Change the four invocation patterns of this, the method invocation pattern and the constructor call pattern will be more and more important, and the function invocation pattern, we must learn to avoid the trap.

If there is a mistake, please reflect in time, I will correct as soon as possible, in case of misleading others, thank you!

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.