The four binding forms of this in the "JavaScript" function

Source: Internet
Author: User

The This and the function in JavaScript are closely related, so today I'll tell you in detail: this in the JavaScript function

When it comes to this, a lot of the abstract concepts that make people dizzy are running out, Here I'll just say the core point-the this in the function always points to the object that called it, the next story will unfold around this point   (remind the front cheese to prepare tea and watermelon, I will start to tell the story!!) )"Story" There was a young man called"Disco" (This)DayDee accidentally crossed into a different world called "Gamma Vascley" (JavaScript).,at this moment Dee was penniless, and the first thing he had to do was to find the place where he was staying--the object that called the functionThe default binding for this

"Story-Line 1" if Diess (this) did not find a place to shelter himself until dark , he saw the life of an African refugee, a benevolent magician, the village chief--window The Savior generally appeared: Live in my house first!

"Body" When a function does not explicitly call an object, that is, when it is simply called as a standalone function,The default binding is used for this function: The Window object bound to the global
function Fire () {     Console.log (this = = window)}fire ();//Output True

The above example I believe is very simple for most people, but sometimes we change the example to be confusing:

Copy Code function Fire () {  //  I am the functions defined inside the function Oh!       function Innerfire () {  Console.log (this = = window      )     } //  Standalone function call  //  output true copy code

The function Innerfire is declared and invoked inside an external function fire, so whose this is it pointing to? Still a window. Many people may be concerned about the effect of the fire function's scope on Innerfire, but as long as we grab our theoretical weapon--without a definite call to the object, we will use the default binding for this function: Bind to the Global window object and you get the right answer. The following example of the enhanced version is also the same output true
var obj = {   fire:function () {       function Innerfire () {          Console.log (this = =  window) 
    }        Innerfire ();    // Standalone function call // Output True       

"Note" In this example, the call to Obj.fire () actually uses the implicit binding of this, which is what I'm going to tell you, and I'll go on to explain the next thing.

"Summary" All things function as an independent function call, regardless of where it is located, its behavior, and directly in the global environment is called the same

This implicit binding "story-Line 2"Diess (This)Cross over to different worlds"Gamma Vascley" (JavaScript), and just got some money on her body, so he found a hotel to stay.

When a function is "contained" by an object, we say that this is implicitly bound to the object , and this allows you to directly access other properties within the bound object, such as the A property below

var obj = {     1,      fire:function () {           Console.log (this. A)        //  Output 1

Now we need to do some deep thinking about the usual code operation, first of all, the following two pieces of code achieve the same effect

// I'm the first piece of code function Fire () {      Console.log (this. A)}  = {      1,      fire:fire   //  //  I am the second segment of code var obj =        {1,        fire:function () {             Console.log (this. a)         //  Output 1
The fire function does not have any difference because it is defined inside and outside of the Obj object, that is, under the two forms of implicit binding above, fire passes this or can access a property within obj, which tells us: 1. This is dynamically bound, or is tied during code run time rather than in the writing period 2. Function-to-object independence, this transfer loss problem (The following description may seem less rigorous with a personal emotional inclination, but this is because I want the reader to understand as much as I want to say) implicit binding, a function that acts as an object property, is independent of the object based on the characteristics of this dynamic binding, written inside the object, as a function of object properties, for this object is independent. (Functions are not " fully owned " by this external object )I would like to say that, in the above, the function is defined inside the object, but it and "declare the function outside the object and then get a reference to the function within the object by the name of the property", both ways is equivalent in Nature ( not just in effect )A function defined inside an object is simply "called by this object", not "born to be called by this object"  Use the this pass-through loss issue in the following implicit binding to illustrate:
var obj = {      1,    //  A is a property defined in object obj   1      fire:function () {   Console.log (this. a)        }      = 2;  // A is the variable defined in the Global Environment    2var fireingrobal = obj.fire;   //   Output 2
The above-mentioned simple codeThe interesting thing is that this reference to the fire function in obj (Fireingrobal) is called, and the behavior (output) is completely invisible and is defined within obj.The reason for this is: we are implicitly bound this is missing!! This is not obj, but the window when the Fireingrobal call is made .The above example changes slightly to become a bug that might bother us:
var a = 2= {    1,    //  A is a property defined in object obj     fire:function () {          Console.log (this. a)     }}  function Otherfire (FN) {     fn ();}   // Output 2

On top of that, our key role is the Otherfire function, which takes a function reference as an argument and then calls it internally, but it does the assumption that the parameter FN is still able to get the A property within obj through this, but in fact, this binding to obj has already been lost, So the output is the global value of a (2), not the value of a within obj (1)

In a string of object property chains, this binds to the most inner objectIn implicit binding, if the function call location is in a string of object property chains, this is the most inner-bound object。 As shown below:
var obj = {      1,      obj2: {           2,           obj3: {                A:3,                geta:function () {                    Console.log (this. a)}}}       Obj.obj2.obj3.getA ();   // Output 3
This explicit binding: (Call and Bind method) "Story-Line 3" diess (this) crossing to different worlds "gamma Vascley" (JavaScript), after hard work, accumulated a certain wealth, so he bought his own house.

Above, we mentioned the problem of this binding being missing from the implicit binding of this.That is, for "Fireingrobal = Obj.fire"The result of the Fireingrobal call and the Obj.fire call is different , because the process of assigning a value to this function does not pass the fire's bound this to the past .。 At this point, the call function comes in handy. basic use of Call: Fn.call (object)FN is the function you call, and the object argument is the one you want the function to bind to. the role of Fn.call (object): 1.Call this function immediately (FN) 2.Call this function when the this function is pointing to object objects example:
var obj = {      1,    //  A is a property defined in object obj       fire:function () {         Console.log (  This . a)       = 2;  // A is a variable  defined in the Global environment var Fireingrobal = Obj.fire;fireingrobal ();    // Output 2 // Output 1
Fireingrobal, which originally lost the this parameter bound to obj, again binds this back to obj. But we don't really like the way that each call relies on calls, we prefer to return a single fireingrobal function that is permanently bound to obj, so that we do not have to call Fireingrobal every time we have to add calls to the tail. What do we do? Smart you can think of, fireingrobal.call (obj) outside the packaging of a function is not possible!
var obj = {      1,    //  A is a property defined in object obj       fire:function () {        Console.log (  This . a)       = 2;  // A is a variable  defined in the Global environment var fn == function () {    fn.call (obj)   // hard bind }        // Output 1

It's easier if you use bind.

var Fireingrobal = function () {    fn.call (obj)   // hard Bind }

Can be simplified to:

var fireingrobal = fn.bind (obj);

the difference between call and bind is:While binding this to the object parameter: 1.call will execute the function immediately 2.bind does not execute functions, only returns a function that is available for execution"Other": As for apply, because in addition to the use of methods, it and call are not very different, here do not repeat here, I put explicit and implicit binding, and the relationship between the function and the object containing the function is likened to the difference between buying a house and renting a room .

For the sake of this

in implicit binding: functions and only temporarily live in "contained objects" in the hotel, it may be a few days later to another hotel to live in Explicit binding: The function will get permanent residency in the "contained object" and will always "live here"The new binding "story" Diess (this) builds up its own family, and when a number of children (through the constructor new many objects) are executed to perform new operations, a fresh object is created, and this of the constructor points to the new object that is created
function foo (a) {     this. A = A;} var a1  New foo (1); var A2     New foo (2), var A3  New foo (3), var a4  new foo (4  // Output 1 // Output 2 // Output 3 // Output 4

Actually, I'm just taking your coffee time to drink beer.

The four binding forms of this in the "JavaScript" function

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.