"This point in JavaScript" issue in a few easy sentences

Source: Internet
Author: User

The This keyword plays a crucial role in JavaScript, and every time it comes along with its point-of-reference, this is where many beginners are prone to error.

However, this article will take you a one-time deal with this point of the problem, hope to help you!

First, who finally call the function, this is pointing to who!

This sentence is to keep in mind the formula, the point of this problem into the analysis to determine the function of the final caller of the question, the following is the explanation and supplement:

①this points to who should not consider where the function is declared, but should consider where the function is called;
②this is always pointing to an object, not a function.
The object that ③this points to is called the context of the function, also called the function's caller.

So the question comes again, how is the final caller of the function determined? Let's first look at an interview question:

read the following code and enter the results.  var length = Tenfunction  fn () {    alert (this. Length)}var obj = {    5,    function(FN) {        fn ()   ///  ?          Arguments[0] ()   //  ?       }}obj.method (FN);

Try to determine, who is the final caller of the function in the problem? With the answer, we continue to look down:

★ ¡ï Two, this point of the law: (with the function of the call way closely related!) )

① is called by the function name () , this always points to window;
② is called by the object. Method , this always points to the object. Obj.func ();
The ③ function acts as an element in the array, called by the array subscript " arr[i" () , which points to the array arr.
The ④ function is used as a callback function for window built-in functions , this points to window;
SetTimeout () setinterval (), etc.
The ⑤ function is called as a constructor using the New keyword, which points to the newly-created object.

According to the above laws, we illustrate each of the following examples:

① is called by the function name () , this always points to window;

    function func () {                Console.log (this);            }            Func (); // function name + () call, this point to window            

② is called by the object. Method , this always points to the object.

    var obj = {                name:"Wq";                Func:func;            }            Obj.func (); // through the object. Method call, this always points to the object. 
    function   () {                document.getElementById() (function  () {                    func (); // function name + () call, this point to window                 }                document.getElementById ("zz"). onclick  = func;   Generalized objects are  passed through an object. Method invocation, this always points to object             }            

The ③ function acts as an element in the array, called by the array subscript " arr[i" () , which points to the array arr.

  var arr [1,2,3,func,4,5,6]  arr[3] ();   function as an element in an array, called by the array subscript "  arr[i" (), this pointer to the array arr

The ④ function is used as a callback function for window built-in functions , this points to widow;

SetTimeout (func,1000); // The function is used as a callback function of the window's built-in function, which points to window;

The ⑤ function is called as a constructor using the New keyword, which points to the newly-created object.

var  The new func ()// function acts as a constructor and is called with the OBJ1 keyword, which points to the newly-created object. 
  var obj1 ={                name:"Obj1",                arr:[func,1,2,3,4]            } obj1.arr[0] ()//  The final caller is an array.  setTimeout (obj1.arr[0],2000); // , called as a built-in function, so this is a pointer to window; settimeout (func,2000);

After a combination of examples to understand these words, we look back at the above interview question:

read the following code, the output should be? varLength = 10functionfn () {alert ( This. Length)}varobj ={length:5, Method:function(FN) {fn ()// ? TenArguments[0] ()// ? 1}}obj.method (FN); Answer: FN ()//10 is called through the function name (), which points to window, which is the global variable length.
Arguments[0] ()///1 function as an element in the array, called by the array subscript " arr[i" () , note that the array at this time is arguments, passed in the argument FN.

Tips

In JavaScript, the arguments object is a more specific object, which is actually a built-in property of the current function. Arguments is very similar to an array, but is not actually an array instance.

The length of the arguments object is determined by the number of arguments, not the number of parameters.

Finally, we will use several questions to consolidate the following:

varFullName = ' John Doe '; varobj ={fullname:' Colin Ihrig ', prop: {fullname:' Aurelio De Rosa ', Getfullname:function() {                     return  This. FullName;            }               }            };             Console.log (Obj.prop.getFullname ()); //The final caller of the function Obj.prop                        varTest =Obj.prop.getFullname;              Console.log (Test ()); //The final caller of the function test () this-> windowObj.func=Obj.prop.getFullname;             Console.log (Obj.func ()); //function Final caller is obj                        vararr = [obj.prop.getfullname,1,2]; Arr.fullname= "Jianghao"; Console.log (arr[0]()); //function Final caller array

If there is a mistake, please contact me! Thank you!

"This point in JavaScript" issue in a few easy sentences

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.