JavaScript's This detailed

Source: Internet
Author: User
The this in JavaScript is always confusing and should be one of JS's well known pits. Personally also think that JS in this is not a good design, due to this late binding characteristics, it can be a global object, the current object, or ... Some people even don't use this because of the big hole.


In fact, if you fully master this principle of work, nature will not enter these pits. Take a look at what this is pointing to in these cases:

1. This in the global Code
1 alert (x);
Global variable x value is 2


The This in the global scope will point to the global object, even if window is in the browser.

2. As a simple function call
function Foocoder (x) {
this.x = x;
}
Foocoder (2);
alert (x);
Global variable x value is 2


Here this points to the global object, which is window. In strict mode, it is undefined.

3. Method calls as objects
var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
Console.log (this.name + "says" + sth);
}
}
Person.hello ("Hello World");

Output foocoder says Hello world. This points to the person object, which is the current object.

4. As a constructor

1 new Foocoder ();

The This within the function points to the newly created object.


5. Intrinsic functions
var name = "Clever coder";

var person = {
Name: "Foocoder",
Hello:function (STH) {
var SayHello = function (sth) {
Console.log (this.name + "says" + sth);
};
SayHello
}

Person.hello ("Hello World");
Clever coder says Hello World


In an intrinsic function, this is not bound to the outer function object as expected, but is bound to the global object. This is generally considered a design error in JavaScript because no one wants the this in the inner function to point to the global object. The general process is to save this as a variable, which is generally agreed to that or self:
var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
var = this;
var SayHello = function (sth) {
Console.log (that.name + "says" + sth);
};
SayHello (STH);
}
}
Person.hello ("Hello World");
Foocoder says Hello World


6. Use call and apply to set this

1 Person.hello.call (person, "world");

Apply and call are similar, except that the arguments that follow are passed in through an array instead of being passed in separately. The method definition for both:

Call (Thisarg [, ARG1,ARG2, ...]);
Parameter list, ARG1,ARG2, ...


Apply (Thisarg [, Argarray]);
Parameter array, Argarray


Both are used to bind a function to a specific object, and this will naturally be set to the first parameter explicitly.

Simply summarize

Simply summing up the above points, it can be found that only the 6th one is confusing.

In fact, you can summarize the following points:

When a function is called as a method of an object, this points to the object.
When the function is called as a fade function, this points to the global object (when strict mode is undefined)
This in the constructor points to the newly created object
This in the nested function does not inherit this from the upper function, and if necessary, it can be saved with a variable.


To summarize the simple point, if this is used in the function, it points to the object only if the function is called directly by an object.
Obj.foocoder ();
Foocoder.call (obj, ...);
Foocoder.apply (obj, ...);

Further

We may often write code like this:

1 $ ("#some-ele"). Click = Obj.handler;

If This,this is used in handler, will it be bound to obj? Obviously not, after the assignment, the function is executed in the callback, and this is bound to the $ ("#some-div") element. This requires understanding the execution environment of the function. This article does not intend to elaborate on the execution environment of functions, but can refer to the implementation environment and scope chain in JavaScript advanced programming. To be pointed out here, understanding the execution environment of the JS function will better understand this.


So how can we solve the problem of callback function bindings? A new method has been introduced in ES5, bind ():
Fun.bind (thisarg[, arg1[, arg2[, ...])

Thisarg

When the binding function is called, the parameter is pointed to when the original function is run. When the binding function is called with the new operator, the parameter is not valid.

1 arg1, arg2, ...

When a binding function is called, these parameters, together with the parameters of the binding function itself, are ordered as arguments to the original function when it is run.


The method creates a new function, called a binding function, which is used as the first parameter of the Bind method when it is created, and the second and later parameters of the incoming bind method plus the parameters of the binding function itself are called in order as arguments to the original function.

Obviously the Bind method can solve the above problem well.
1
2 $ ("#some-ele"). Click (Person.hello.bind (person));
When the corresponding element is clicked, the output foocoder says Hello World


In fact, the method is also very easy to simulate, we look at the Prototype.js bind method source code:
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call (arguments), object = Args.shift ();
return function () {
Return Fn.apply (object,
Args.concat (Array.prototype.slice.call (arguments)));
};
};

  • 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.