About this in the JavaScript function

Source: Internet
Author: User

Body

The This and the function in JavaScript are closely related, so today I'll give you a detailed account of this: in the JavaScript function, this one comes out with a lot of dizzy, abstract concepts. 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),One day, Diess accidentally crossed into a called "Gamma Vascley" (JavaScript)Different world, and 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 invokes the function

Back to the top of this default binding

"Story-Line 1" if Diess (this) did not find a place to take shelter until dark, he saw the life of an African refugee, A benevolent magician village chief--windowThe 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, it uses the default binding 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:
function Fire () {//I am the functions defined inside the function Oh! function Innerfire () {Console.log (this = = window)} innerfire (); Independent function call}fire (); Output true

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)} inner   Fire (); Independent function call}}obj.fire (); 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 sameBack to the top of this implicit binding "story-Line 2" diess (this) crossing to different World "gamma Vascley" (JavaScript), just on the body with some money, so he found a hotel to stay down

When a function is "contained" by an object, we say that this is implicitly bound to the object., this allows you to directly access other properties within the bound object, such as the A property below
var obj = {a:1, fire:function () {console.log (THIS.A)}}obj.fire (); Output 1

Now we need to do some deeper thinking about the usual common code operation, first of all, the following two pieces of code achieve the same effect:
I am the first Code function fire () {Console.log (THIS.A)} var obj = {a:1, fire:fire}obj.fire ();  Output 1//I am the second segment of code var obj = {a:1, fire:function () {console.log (THIS.A)}}obj.fire (); 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.and not just the 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 = {a:1,//A is a property defined in object obj   1 fire:function () {Console.log (THIS.A)}} var a = 2  ;  A is a variable defined in the Global environment  2var fireingrobal = Obj.fire; Fireingrobal (); Output 2

The above-mentioned simple code The 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;var obj = {a:1,//A is a property defined in object obj fire:function () {Console.log (THIS.A)}} function O  Therfire (FN) {fn ();} Otherfire (Obj.fire); 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 object In 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 = {a:1, obj2: {         a:2,         obj3: {                a:3,                geta:function () {Console.log                   (THIS.A)                      }           }  }} Obj.obj2.obj3.getA (); Output 3

Back to the top of 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 results of the Fireingrobal call and the Obj.fire call are differentbecause 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 = {a:1,//A is a property defined in object obj fire:function () {Console.log (THIS.A)}} var a = 2;   A is the variable var fireingrobal = Obj.fire;fireingrobal () defined in the Global environment; Output 2fireingrobal.call (obj); 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 = {a:1,//A is a property defined in object obj fire:function () {       console.log (THIS.A)}} var a = 2; A is a variable that is defined in the Global environment var fn = Obj.fire;var Fireingrobal = function () {fn.call (obj)//Hard Bind} fireingrobal (); 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"Back to the top new binding "story" Diess (this) set up his own family and gave birth to multiple children (many objects are new through the constructor function)

When you perform a new operation, a fresh object is created, and this point 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 ); Console.log (a1.a); Output 1console.log (a2.a); Output 2console.log (a3.a); Output 3console.log (a4.a); Output 4

Thank you, everyone!!

About this in the JavaScript function

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.