"Turn" in layman's JavaScript

Source: Internet
Author: User
Tags uppercase letter

In object-oriented languages such as Java, the meaning of the This keyword is explicit and specific, that is, referring to the current object. It is generally determined at compile time, or as a compile-time binding. In JavaScript, this is a dynamic binding, or a run-time binding, which leads to the ability of the This keyword in JavaScript to have multiple meanings, as well as to bring flexibility and confusion for beginners. This article only discusses this issue, read this article, if the reader can correctly answer the question of what is in JavaScript, as the author, I would feel that it took so much effort to write such an article is worthwhile.

This in the Java language

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.

Listing 1. Point.java
public class Point {     private int x = 0;     private int y = 0;         Public point (x, y) {         this.x = x;         This.y = y;     }         Public point (Y) {This         (0, y);     }  }

Back to top of page

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.

Listing 2. Point.js
var point = {  x:0,  y:0,  moveto:function (x, y) {      this.x = this.x + x;      This.y = This.y + y;      }  };  Point.moveto (1, 1)//this bind 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.

Listing 3. Nonsense.js
function Makenosense (x) {  this.x = x;  }  Makenosense (5);  x;//x has become a global variable with a value of 5

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.

Listing 4. Point.js
var point = {  x:0,  y:0,  moveto:function (x, y) {      //internal function     var MoveX = function (x) {      this.x = x Where did the//this bind to?    };     Intrinsic    var movey = function (y) {     this.y = Y;//this bound to where?    };     MoveX (x);     Movey (y);     }  };  Point.moveto (1, 1);  Point.x; ==>0  point.y;//==>0  x;//==>1  y;//==>1

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, the clever JavaScript programmer came up with a variable substitution method, conventional, the variable is generally named that.

Listing 5. Point2.js
var point = {  x:0,  y:0,  moveto:function (x, y) {       var. = this;      Intrinsic     var MoveX = function (x) {      that.x = x;      };      Intrinsic     var movey = function (y) {      that.y = y;      }      MoveX (x);      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.

Listing 6. Point.js
function point (x, y) {     this.x = x;     This.y = y;  }
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:

Listing 7. Point2.js
function point (x, y) {     this.x = x;     This.y = y;     This.moveto = function (x, y) {         this.x = x;         This.y = y;     }  }  var p1 = new Point (0, 0);  var P2 = {x:0, y:0};  P1.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.

A different angle to understand

If like the author, we also think that the above four ways not easy to remember, after a period of time, and do not understand what this refers to. So I recommend this article to Yehuda Katz: Understanding JavaScript Function Invocation and "this". In this article, Yehuda Katz takes the method of apply or call as the basic way of function invocation, and several other ways are evolved on this basis, or called syntactic sugars. Yehuda Katz emphasizes the process of this binding on a function call, regardless of how the function is called, to complete the binding process, unlike when the this is bound to a global object as a function call, and when called as a method, this binds to the object to which the method belongs.

End?

By the above description, if you have been able to clearly distinguish the meaning of this in various situations, the goal of this article has been completed. If you're a bit more curious about why this is so rich in JavaScript, you'll have to read the following. The author needs to inform you in advance that the content below will be slightly more boring than before, and if you just want to understand the meaning of this, it's enough to read it. If everyone is not too boring, but to explore the question, then go into the next section together.

Back to top of page

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 creates a arguments variable that contains the arguments passed in when the function is called. Next, create the scope chain. Then initialize the variable, initialize the function's formal parameter list first, the value is the arguments corresponding value in the variable, and if arguments there is no corresponding value in the variable, the parameter is initialized undefined . If the function contains intrinsic functions, the intrinsic functions are initialized. If not, continue to initialize the local variables defined within the function, it is important to note that at this time the variables are initialized undefined , and their assignment is executed when the execution Environment (EXECUTIONCONTEXT) is successfully created, which is why we understand JavaScript The scope of the variables in is very important, given the length, we will not discuss this topic here. Finally, this assign a value to the variable, as described above, depending on how the function is called, assign to the this global object, the 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).

Function.bind

With the previous description of the function execution environment, let's look at a situation where this is often misused in JavaScript: a callback function. JavaScript supports functional programming, which is a level object that can be passed as a parameter. Consider the following example, Myobject.handler, as a callback function, is invoked when the onclick event is triggered, but at this point the function is already executed in another execution environment (ExecutionContext), and this is naturally not bound to MyObject Object.

Listing 8. Callback.js
Button.onclick = Myobject.handler;

This is a common mistake that JavaScript novices often make, and in order to avoid this error, many JavaScript frameworks provide a way to manually bind this. Dojo, for example, provides Lang.hitch, which takes an object and function as arguments, returns a new function, and executes the this binding on the incoming object. Using Dojo, you can change the above example to read:

Listing 9. Callback2.js
Button.onclick = Lang.hitch (MyObject, Myobject.handler);

In the new version of JavaScript, a built-in bind method has been provided for everyone to use.

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.

Back to top of page

Conclusion

This article describes the meaning of the This keyword in JavaScript in a variety of situations, although this is only a small concept in JavaScript, but we can take a closer look at the execution environment of functions in JavaScript, which is the basis for understanding other concepts such as closures. With these concepts in hand, it is possible to fully exploit the features of JavaScript before discovering the power of JavaScript language features.

"Turn" in layman's 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.