The This keyword in javascript

Source: Internet
Author: User
Tags uppercase letter

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) {
Intrinsic functions
var MoveX = function (x) {
This.x = X;//this bound to where?
};
Intrinsic functions
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 functions
var MoveX = function (x) {
That.x = x;
};
Intrinsic functions
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.
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 the arguments variable, which 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 corresponding value in the arguments variable, and if there is no corresponding value in the arguments variable, the parameter is initialized to 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 when these variables are initialized to undefined, 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, assign a value to the this variable, as described earlier, 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.
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.

(Transferred from the network)

The This keyword in javascript

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.