Javascript: this _ basic knowledge-js tutorial

Source: Internet
Author: User
This article mainly introduces this in Javascript. If you need this, you can refer to it. Introduction
This plays a very important role in various opposite object programming and is mainly used to point to the called object. However, in JavaScript, the performance of this varies greatly, especially in different execution contexts.

We know from the previous article that this is also an attribute in the execution context, and it is destined to be irrelevant to the execution context.

The Code is as follows:


ActiveExecutionContext = {
VO :{...},
This: thisValue };

In Javascript, the value of this depends on the call mode. There are four call modes: method call mode, function call mode, constructor call mode, and apply call mode.

Call Mode
Method call mode
When a function is saved as an attribute of an object, we call it a method. When a method is called, this is bound to this object, that is, this in method call mode points to the called object. This is easy to understand. You are one of my methods. You belong to me. Of course, your this point points to me.

The Code is as follows:


Var myObject = {
Value: 0,
Increment: function (inc ){
This. value + = typeof inc = "number "? Inc: 1;
}
}
MyObject. increment ();
Console. log (myObject. value); // output: 1
MyObject. increment (3 );
Console. log (myObject. value); // output: 4

Because this can be used to access the object to which it belongs, all attributes or methods in the object can be called and modified through this. As mentioned above, this is a member of the execution context attribute, which must be created only when the context is created. All the binding of this to the object occurs during the call, this is "delayed binding ". This can be highly reused through delayed binding.

The Code is as follows:


Function showValue (){
Console. log (this. value );
}
Var a = {value: ""};
Var B = {value: "B "};
A. showValue = showValue;
B. showValue = showValue;
A. showValue (); // output ""
B. showValue (); // output "B"

In the above example, the showValue function is a delayed binding.

Function call mode
A function is called when it is not called as a method of an object. In function call mode, this is bound to a global object. (This is a language design error)

The Code is as follows:


MyObject. double = function (){
Var that = this; // Solution
Var helper = function (){
Console. log (that, ":", that. value); // output Object {value: 4, increment: function, double: function} ":" 4
Console. log (this, ":", this. value); // output Window {top: Window, window: Window ...} ":" Undefined
}

Helper (); // called as a function
}

According to the normal idea, this points to the object to which the function belongs, as output in the fourth line. However, this points to a global object due to problems in the language design. This makes this mysterious and unpredictable. However, as developers, this situation must be something we don't want to comment on. If we don't play the cards as common sense, it's okay that the remedy is simple. that is, in the above example, we use that to refer to this. In this way, calling that in the helper method can be used as this, which is simple and convenient. The reason why this is the function call mode is like this is described in detail later when analyzing the reference type.

Constructor call mode
Javascript is based on prototype inheritance, but its designers want it to create objects through new and constructor, just like the traditional object-oriented language. This doesn't seem to be a good idea, and it's a bit embarrassing to draw a tiger out of anti-type dogs. First, it is not necessary to learn. The prototype Inheritance Mechanism of javascript is powerful enough to meet the inheritance polymorphism required by object-oriented programming.

Let's talk about the constructor call mode. The constructor call mode is very simple, it is a function as the constructor, and then introduce the attributes and methods you intend to share with this declaration. As follows:

The Code is as follows:


Function Person (name, age ){
This. name = name;
This. age = age;
This. say = function (){
Console. log ("name: % s, age: % n", this. name, this. age );
}
}

Var p1 = new Person ("jink", 24 );
P1.say (); // output name: jink, age: 24

Var p2 = new Person ("James", 33 );
P2.say (); // output name: James, age: 33

The above example clearly shows that this is an object created through the new and constructor. Why? This is because when the new constructor is called in javascript, the new operator calls the [[Construct] Method in the "Person" function. After the object is created, call the internal [[Call] method. All the same function "Person" sets the value of this as the newly created object.

Apply call mode
After all functions in javascript are created, two methods are provided: apply and call. I don't want to describe the specific use of these two methods here. If you don't know how to use them, you can use Baidu, which is quite simple. You can set this manually in two ways. Although this cannot be modified during creation, it is another thing that we have set manually before creation. This setting is incredible. You can make your object call any method, as if you could let the car sail in the sea, the African elephant flies like a leopard, and the programmer plays like a piano player. Haha imagine that it is always good. Call is called, but if the call can implement the function, let's talk about it.

The Code is as follows:


Var programmer = {
Name: "programmer ",
Hand: "flexible hands ",
Programme: function (){
Console. log (this. name + "use" + this. hand + "to write code. ");
}
}

Var pianist = {
Name: "Pianist ",
Hand: "flexible hands ",
Play: function (){
Console. log (this. name + "use" + this. hand + "to play beautiful music. ");
}
}

Var player = {
Name: "athlete ",
Foot: "healthy legs ",
Run: function (){
Console. log (this. name + "use" + this. foot + "is running on the stadium. ");
}
}

// Follow the rules
Programmer. programme (); // programmers write code with flexible hands.
Pianist. play (); // The piano uses flexible hands to play beautiful music.
Player. run (); // athletes are running on the stadium with strong legs.
// Whimsical
Pianist. play. apply (programmer); // programmers can play beautiful music with flexible hands.
Player. run. apply (programmer); // The programmer uses undefined to run the game. Because of its lack of sports, there is no strong legs

It seems interesting. The first parameter of apply is the point of this in the execution method. In this way, we can use other people's methods to secretly use them, which is very convenient. These skills are often used in some frameworks.

Summary
So much about this. I believe that after reading this, I have some knowledge about this determination in different situations. I was going to discuss the reference object next, describe the principle of this value in the method call mode and function call mode, but fear that the length is too long. Therefore, we decided to use a single chapter to analyze the concept of referencing objects.

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.