The This in JavaScript

Source: Internet
Author: User
Tags uppercase letter

Introduction  

JavaScript is a scripting language, so many people think it's easy to learn. In contrast, JavaScript supports advanced features such as functional programming, closures, and prototype-based inheritance. This article only picks one example: The This keyword in JavaScript, to analyze its meanings in different situations, the reasons for this situation, and the method of binding this provided in JavaScript tools such as Dojo.

java

Defining a class in Java often uses the This keyword, in most cases to avoid naming conflicts, for example, in the following example, defining a point class, it is natural to use X, y to name its properties or member variables, in the constructor, using X, y to name the parameter, compared to other names, such as a, B, also more meaningful. This is the time you need to use this to avoid naming conflicts. Another case is to make it easier to call other constructors, such as those defined on the x-axis, whose X-value defaults to 0, and as long as the Y value is supplied, we can define a constructor that simply passes in one argument. In either case, this means the same, meaning the current object. Such as:

1  Public classPoint {2     Private intx = 0; 3     Private inty = 0; 4     5      PublicPoint (x, y) {6          This. x =x;7          This. y =y;8     } 9     Ten      PublicPoint (y) { One          This(0, y);  A     }  -}
This in the JavaScript language

Because of the nature of its run-time bindings, this meaning in JavaScript is much richer, and it can be a global object, the current object, or any object, depending on how the function is called. The invocation of a function in JavaScript has several ways: as an object method call, as a function call, as a constructor call, and with an apply or call invocation. Below we will discuss the meaning of this separately, depending on the invocation method.

Called as an object method

In JavaScript, a function is also an object, so a function can be a property of an object, at which point it is called a method of the object, which is naturally bound to the object when this invocation is used. Examples are as follows:

1var point = { 2x:0, 3y:0, 4 moveto:function (x, y) {5       This. x = This. x +x;6       This. y = This. Y +y;7      } 8  }; 9 TenPoint.moveto (1, 1)//This binds to the current object, which is the point object

As a function call

The function can also be called directly, at which point this is bound to the global object. In the browser, window is the global object. For example, the following example: When a function is called, this is bound to a global object, and the next execution of an assignment statement is tantamount to implicitly declaring a global variable, which is clearly not what the caller wants. Examples are as follows:

12 This  . x =34 5  Makenosense (56  x;   X has become a global variable with a value of 5

( note ) for intrinsic functions, which are functions that are declared in the body of another function, this way of binding to a global object creates another problem. We still use the point object mentioned earlier as an example, this time we want to define two functions within the MoveTo method, translating the x, y coordinates, respectively. The result may be unexpected, not only the point object does not move, but more than two global variables x, Y. Examples are as follows:

1var point = { 2x:0, 3y:0, 4 moveto:function (x, y) {5      //intrinsic Functions6var MoveX =function (x) {7       This. x = x;//where is this bound to? 8     }; 9     //intrinsic FunctionsTenvar Movey =function (y) { One      This. y = y;//where is this bound to?  A     };  -  - MoveX (x); the Movey (y); -     }  -  };  -Point.moveto (1, 1);  +Point.x;//==>0 -Point.y;//==>0 +X//==>1 AY//==>1

( solution ) This is a JavaScript design flaw, the correct design is that the internal function of this should be bound to its outer function corresponding to the object, in order to circumvent this design flaw, smart JavaScript programmers come up with a variable substitution method, the conventional , the variable is typically named that. Improvements are as follows:

1var point = { 2x:0, 3y:0, 4 moveto:function (x, y) {5var that = This; 6      //intrinsic Functions7var MoveX =function (x) {8That.x =x;9      }; Ten      //intrinsic Functions Onevar Movey =function (y) { AThat.y =y; -      }  - MoveX (x); the Movey (y); -      }  -  };  -Point.moveto (1, 1);  +Point.x;//==>1 -Point.y;//==>1

Called as a constructor function

JavaScript supports object-oriented programming, unlike mainstream object-oriented programming languages, where JavaScript does not have the concept of classes (class), but rather uses a prototype-based (prototype) approach to inheritance. Correspondingly, the constructors in JavaScript are also very special, as are normal functions if not called with new. As another rule of law, the constructor starts with an uppercase letter, reminding the caller to invoke it in the correct way. If called correctly, this binds to the newly created object. Examples are as follows:

12     this. x =3this     . y =4   }

Invoke with apply or call
Let us again reiterate that in JavaScript functions are objects, objects have methods, and apply and call are methods of function objects. These two methods are exceptionally powerful, and they allow the switch function to execute the context (contextual), which is the object of this binding. This method is used in many JavaScript techniques as well as in class libraries. Let's look at a specific example:

1 functionPoint (x, y) {2      This. x =x;3      This. y =y;4      This. MoveTo =function(x, y) {5          This. x =x;6          This. y =y;7     } 8  } 9 Ten  varP1 =NewPoint (0, 0);  One  varP2 = {x:0, y:0};  AP1.moveto (1, 1);  -P1.moveTo.apply (P2, [10, 10]);

In the example above, we use the constructor to generate an object P1, which has a moveTo method, and another object is created using the object literal P2, and we see that using apply can apply the P1 method to P2, when this is also bound to the object P2. Another method call has the same function, the difference is that the last parameter is not uniformly passed in as an array, but separately passed in.

execution Environment for functions

A function in JavaScript can be executed as a normal function or as a method of an object, which is the main reason for the richness of this meaning. When a function is executed, an execution environment (ExecutionContext) is created, and all the behavior of the function occurs in this execution environment, when the execution environment is built, JavaScript first createsargumentsVariable that contains the arguments passed in when the function is called. Next, create the scope chain. Then initialize the variable, first initializing the function's formal parameter list, and the value is argumentsThe corresponding value in the variable, if argumentsThere is no corresponding value in the variable, the parameter is initialized to undefined。 If the function contains intrinsic functions, the intrinsic functions are initialized. If not, continue initializing the local variables defined within the function, and be aware that these variables are initialized to undefined, the assignment operation executes when the execution environment (EXECUTIONCONTEXT) is successfully created, which is important for us to understand the scope of variables in JavaScript, and we will not discuss this topic in the first place, given the length. Finally for thisVariable assignment, as described earlier, is assigned to a method depending on how the function is called. this Global Object, current object, and so on. The execution Environment (EXECUTIONCONTEXT) of the function is created successfully, the function begins to execute line by row, and the required variables are read from the previously built execution Environment (EXECUTIONCONTEXT).

eval Method

The Eval method in JavaScript can convert a string to JavaScript code, where does this point when using the Eval method? The answer is simple, see who is calling the Eval method, and this in the caller's execution Environment (ExecutionContext) is inherited by the Eval method.

The This in JavaScript

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.