Read more about the basic usage of-this-keywords in global, function, object, jquery!

Source: Internet
Author: User
Tags jquery library

First, preface

1, JavaScript is an object-based dynamic language, that is, everything is an object, a very typical example is that the function is also considered a normal object. JavaScript can implement object-oriented programming through certain design patterns, where this "pointer" is an important feature of implementing object-oriented. But this is also a very easy-to-understand and wrong-to-use feature in JavaScript.

2, this is a keyword in the JavaScript language. It represents an internal object that is automatically generated when the function is run.

Second, get to the point 1, the--this in the global code

1, the browser host in the Global environment, this refers to the window object. In global code, this is always the global object itself, so it is possible to refer to it indirectly.

Example:

<script type= "Text/javascript" >        console.log (this),//window        console.log (this = = window);//true </script>

2, in the browser in the global environment, the use of var declaring variables will assign the value this or window .

Example:

<script type= "Text/javascript" >        var  name = "Jack" ;        Console.log (this.name);//jack        Console.log (window.name);//jack</script>

  3, in any case, even if the creation of a variable is not used var , is also the operation of the global this . When you create a variable inside a function, the result is undefined.

Example:

<script type= "Text/javascript" >    name = "Jack";    function Testthis () {Age         = +;         Console.log (This.age);     Console.log (this.age);//undefined     console.log (this.name);//Jack testthis (); Console.log (this.name);//jack</script>     
--this in the function code

1, first look at one of the simplest examples

<script type= "Text/javascript" >    var name = "Jack";    function Sayhi () {      console.log ("Hello, my name is" + name);//"Hello, my name is Jack"      console.log ("Hello, my name is" + this.name); /"Hello, my name is Jack"    }    sayhi ();</script>  

First, we define a global string object name and function object Sayhi. The run will print out, "Hello, my name is Jack". The global variable name assigns the value to this.

2, we change the above code to change:

<script type= "Text/javascript" >    name = "Jack";    function Testthis () {      this.name = "Alice";    }    Console.log ("Hello, my name is" +this.name);  "Hello, my name is Jack"    testthis ();    Console.log ("Hello, my name is" +this.name);  "Hello, my name is Alice" </script>    

The result of the operation is that this is the global variable Name=jack in jack before the function call and assigns the value to this, at which point the Textthis function does not assign Alice to this ; The Testthis function assigns the Alice value to the global variable name when Alice is the function call, and name = "Alice" this.name = "Alice".

3, the function is also an ordinary object, it can be used as a common variable. Let's change the code above:

<script type= "Text/javascript" >    var name = "Jack";    function Sayhi () {       console.log ("Hello, my name is" + this.name);//undefined    }    var person = {};    Person.sayhello = Sayhi;    Person.sayhello (); </script>//and define person  = {Name:alice}  , then: <script type= "Text/javascript" >    var name = "Jack"; function Sayhi () {console.log ("Hello, my name is" + this.name);//"Hello, my name is Alice" } var per son = {Name:alice}; Person.sayhello = sayhi; Person.sayhello ();</script>    

First, we define a global function object Sayhi and execute this function, and the function internally uses the This keyword, then the object that executes this line of code is SAYHI (the embodiment of all objects), Sayhi is defined in the global scope. In fact, the so-called global object in JavaScript is nothing more than a property defined under the root object of window. Therefore, the owner of the Sayhi is the Window object. That is, under global scope, you can refer to the object by using name directly, or you can refer to the same object by Window.name. Thus this.name can be translated into Window.name.

Second, we define the object of a person and define its SayHello property, which points to the Sayhi global object. So this time, When we run Person.sayhello, this is where the code belongs to the object is SayHello (in fact, Sayhi and SayHello is just like two pointers, pointing to the object is actually the same), and the owner of the SayHello object is the person. For the first time, there is no Name attribute in person, so the dialog box that pops up is this.name refers to the undefined object (all variables in JavaScript that are declared but not defined all point to the undefined object ) And the second time we add the name attribute when we define the person, then the nature that this.name points to is our defined string.

As explained above, we have transformed the example above into an object-oriented code:

<script type= "Text/javascript" >    var name = "Jack";    function Sayhi () {       console.log ("Hello, my name is" + this.name);//Two function calls were successful and printed two times: "Hello, my name is marry"     "Hello, my name is Alice. "    }    function person (name) {        this.name = name;    }    Person.prototype.sayHello = Sayhi, var marry = new Person ("marry"), Marry.sayhello (), var alice = new Person ("Al Ice "); Alice.sayhello ();</script>       

In the above code, we define a person's "class" (actually an object), and then define the SayHello property in the prototype of the class (The class prototype is equivalent to a static member variable in C + + ), which points to the global Sayhi object. Running the code we can see that both marry and Kevin have successfully printed it out.

4. When using the calling function, the new keyword is used to this refer to a new context, no longer pointing to the globalthis。通常我将这个新的上下文称作实例。

<script type= "Text/javascript" >    name = "Jack";    function Testthis () {      this.name = "Alice";    }    Console.log (this.name); "Jack"    new testthis ();    Console.log (this.name); "Jack" Console.log (New Testthis (). name);//"Alice" </script>     

Iii.--this in the object code

1. You can access the properties of the object by using it in any method of the object this . This new is not the same as using the resulting instance.

var obj = {   name: "Jack",    func:function () {        console.log (this.name);//   "Jack"     }};obj.func ();   

2. You can bind a function to an object as if the object were an instance.

var obj = {    name: "Jack"};function logName () {    console.log (this.name);//logs "Jack"} Logname.apply (obj);   

3. You can also this access the properties of an object directly without passing it.

var obj = {   name: "Jack",    deeper: {        logname:function () {            console.log (obj.name);//    "Jack"        }       
Iv.--this in the jquery code

1. Most places in the jquery library this are also referred to as DOM elements. The event callbacks on the page and some handy static methods like $.each this one.

<div class= "foo bar1" ></div><div class= "foo bar2" ></div><script src= ". /05-jquery/js/jquery-1.10.2.min.js "></script><script type=" Text/javascript ">$ (function() {     $ (". Foo"). each (function () {            console.log (this);//  <div class= "foo bar1" ></div>   <div class= "foo bar2" ></div>        });        $ (". Foo"). On ("click", Function () {            console.log (this);//  <div class= "foo bar1" >   <div class= "foo bar2" ></div> }); }) </script>     

End:

Above, is the Bo master himself in the process of practice, summed up a bit of experience, I hope that everyone can help, welcome you can put forward noble opinion, Bo Master fixed when the supplementary correction.

 

  

  

Read more about the basic usage of-this-keywords in global, function, object, jquery!

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.