Learn JavaScript with me this keyword _javascript tips

Source: Internet
Author: User
Tags closure

This article only discusses this question, after reading this article, if the reader can correctly answer the What ' s This question in JavaScript, as the author, I may feel that spends so much effort, writes such an article is worth.

Let's remember a word: Thisalways points to the object where the function is running! Instead of the object where the function was created. Also namely: Who calls, points to who. Remember ...

This article will be divided into three different scenarios to analyze where the this object is.
1, the ordinary function of this
No matter where this is, the first priority is to find the location of the function at run time.

 var name= "global";
 function GetName () {
   var name= "local";
   return this.name;
 };
 Alert (GetName ());

When this appears in the function GetName of the global environment, the position of the function GetName at runtime is

Alert (GetName ());

Obviously, the object of the function GetName is the global object, the window, so the home of this is definitely in window. This point to the Window object, then the GetName returned THIS.name is actually window.name, so alert is "global"!

So where does this not appear in the global environment's function, but in the local environment's function?

 var name= "global";
 var xpg={
   Name: "Local",
   Getname:function () {return
     this.name;
   }
 };
 Alert (Xpg.getname ());

The function in which this body is getname is not in the global environment, but in the XPG environment. Wherever this is located, be sure to find the location of the function at run time. Where the function getname at run time

Alert (Xpg.getname ());

Obviously, the function getname is the object of the XPG, so this is the place of the XPG, that is to point to Xpg object, then GetName returned this.name is actually xpg.name, so alert out is "local"!

To give an example of consolidation:

var someone = {
  name: "Bob",
  showname:function () {
    alert (this.name);
  }
;

var other = {
  name: "Tom",
  showName:someone.showName
}

other.showname (); Tom

This keyword, although declared in Someone.showname, is other.showname at run time, so this points to the current object of the Other.showname function, other, so the last alert is other.name.

2, the closure of this

Closure is also a restless, this article is not too much to repeat, in short: the so-called closure is to create another function inside a function, and the internal function access to external variables.
The prodigal son this and the ruffian closes the bag to mix together, visible will Yongwuningri Ah!

 var name= "global";
 var xpg={
   Name: "Local",
   Getname:function () {return
     function () {return
       this.name;
     }
 ;}}; Alert (Xpg.getname () ());

This is obviously in a dilemma, in the anonymous function in the GetName function, and the anonymous function calls the variable name, which makes up the closure, that is, the closure of the package.
Wherever this is located, be sure to find the location of the function at run time. It cannot be judged by the position of the function getname the runtime, but by the run-time position of the anonymous function.

function () {return
  this.name;
};

Obviously, the anonymous function is the object of the window, so this is the home of the window, then the anonymous function returned this.name is actually window.name, so alert out of the "global"!

So how do you make this a xpg in a closure? -Caching this

 var name= "global";
 var xpg={
   Name: "Local",
   getname:function () {
     var that=this;
     return function () {return
       that.name;
 };}}; Alert (Xpg.getname () ());

Define That=this in the GetName function, at which point the GetName function runs at

Alert (Xpg.getname ());

Then this points to the Xpg object, so that is also pointed to the Xpg object. In the closure of the anonymous function return That.name, then the return of the That.name is actually xpg.name, so you can alert out "local"!

3, New keyword to create an object

This in the constructor after the new keyword points to a new object constructed with the constructor:

function Person (__name) {
  this.name = __name;    This is a new object constructed with this constructor, this example is Bob object
}
Person.prototype.show = function () {
  alert (this.name);  This points to Person,this.name = Person.name;
}

var bob = new Person ("Bob");
Bob.show ();    Bob

4, call and apply in the This

The estimate of this in JavaScript can be no more than call and apply.
Call and apply are like the parents of this, let this live where it will have to live, have to obey! When there is no argument, the current object is window

var name= "global";
var xpg={
  Name: "Local"
};
function GetName () {
  alert (this.name);
}
GetName (XPG);
Getname.call (XPG);
Getname.call ();

Where this is in the function GetName. Wherever this is located, be sure to find the location of the function at run time. Where the function getname at run time

GetName (XPG);

Obviously, the function getname is the object of the window, so this is a safe place in the window, that point to the Window object, then GetName return this.name is actually window.name, so alert out of the "global"!

So, the call and apply are on, because this must listen to their command!
Getname.call (XPG);
In which, call specifies the home of this is in the Xpg object, because this is forced only in xpg that the home, then this point to Xpg object, THIS.name is actually xpg.name, so alert out is "local"!

5. This in eval

For the Eval function, it does not seem to specify the current object at its execution time, but in fact it does not point to window because the function executes at the current scope, which is equivalent to the code inside the line. The following example illustrates the problem:

var name = "Window";

var Bob = {
  name: "Bob",
  showname:function () {
    eval ("Alert (this.name)");
  }
;

Bob.showname ();  Bob

6, no explicit current object when the This

This points to the Global object window when there is no explicit execution of the current object.
For example, for a function referenced by a global variable, we have:

var name = "Tom";

var Bob = {
  name: "Bob",
  show:function () {
    alert (this.name);
  }

var show = Bob.show;
Show (); Tom

You may also be able to understand that show is the method under the Window object, so the current object at execution time is window. However, the functions referenced by local variables do not explain this:

var name = "Window";

var Bob = {
  name: "Bob",
  Showname:function () {
    alert (this.name);
  }
;

var tom = {
  name: "Tom",
  Showname:function () {
    var fun = bob.showname;
    Fun ();
  }
;

Tom.showname (); Window

The current object in the browser when settimeout, setinterval, and anonymous functions are executing is the Global object window, which we can consider to be a special case of the previous one.

var name = "Bob"; 
var nameobj ={ 
   Name: "Tom", 
   showname:function () { 
     alert (this.name); 
   }, 
   waitshowname:function () { 
     settimeout (this.showname, 1000); 
   } 
 }; 

 Nameobj.waitshowname ();

So at the time of running This.showname, this points to window, so it finally shows Window.name.

7, this in the DOM event

(1) You can use it directly in the DOM element

<input id= "btntest" type= "button" value= "Submit" onclick= "alert (this.value)"/>

Analysis: An onclick (or other such as onblur, etc.) attribute of a DOM element that is owned by the HTML element it belongs to, and written directly in the function it triggers this,this should point to the HTML element.

(2) Register JS function for DOM element
A, not the right way

<script type= "Text/javascript" >
 function Thistest () {
 alert (this.value);//pop-up undefined, this points here??
}
</script>
<input id= "btntest" type= "button" value= "Submit" onclick= "Thistest ()"/>

Analysis: The onclick event calls the Thistest function directly, and the program pops up the undefined. Because the Thistest function is defined in the Window object,
So the owner of the Thistest (scope) is window,thistest This is also window. Window does not have the value attribute, so it is an error.
b, the right way

<input id= "btntest" type= "button" value= "Submit"/> <script type= "

text/javascript" >
 function Thistest () {
 alert (this.value); 
}
document.getElementById ("Btntest"). Onclick=thistest; Register a function for the button's onclick event
</script>

Analysis: In the previous example, the Thistest function is defined in the global scope (here is the Window object), so this refers to the current Window object. and through document.getElementById ("btntest"). Onclick=thistest, in this form, is to set the Btntest onclick property to a copy of the Thistest function, Within the function scope of the Btntest onclick property, this is btntest all, and this points to btntest. In fact, if there are multiple DOM elements to register the event, we can take advantage of different DOM element IDs and implement them in the following ways:

document.getElementById ("Domid"). Onclick=thistest; Registers a function with the button's onclick event.

Because many different HTML elements create different copies of the function, the owner of each copy is the corresponding HTML element, each of which points to their owner, without causing confusion.
To verify the above, let's improve the code so that the button pops up their corresponding triggering function directly:

<input id= "BtnTest1" type= "button" value= "Submit 1" onclick= "thistest ()"/> <input id= "btnTest2"
type= "button "Value=" Submit 2 "/>

<script type=" text/javascript ">
function Thistest () {
this.value=" submit ";
}
var Btn=document.getelementbyid ("BtnTest1");
alert (Btn.onclick); The first button function

var btnother=document.getelementbyid ("BtnTest2");
Btnother.onclick=thistest;
alert (Btnother.onclick); The second button function
</script>
Its pop-up result is:

//The first button functions
onclick () {
 thistest ()
}

The second button
function thistest () {
 this.value= "in Commit";
}

From the above results you must understand more thoroughly.
By the way, every copy of a new function is created, and the program assigns a certain amount of memory to the copy of the function. In practical applications, most functions are not necessarily called, so this part of the memory is wasted. So this is what we usually write:

<input id= "BtnTest1" type= "button" value= "Submit 1" onclick= "thistest (This)"/> <input id= "BtnTest2" type= "
Button "Value=" Submit 2 "onclick=" Thistest (This) "/> <input id=" btnTest3 "
button" type= "Submit 3" value= " Thistest (This) "/> <input id= btnTest4" type= "
button" value= "Submit 4" onclick= "Thistest (This)"/>

< Script type= "Text/javascript" >
 function thistest (obj) {
 alert (obj.value); 
}
</script>

This is because we use the method of function reference, the program will only allocate memory to the function's ontology, and reference only assign pointers. Write a function so that it assigns a (pointer) reference to it, which is much more efficient. Of course, if you think this registration event cannot be compatible with multiple browsers, you can write the following generic script for the registration event:

JS event Add eventutil.addevent (DOM element, event name, event-triggered function name) remove eventutil.removeevent (DOM element, event name, event-triggered function name) var eventutil = new

EventManager (); JS Event General Manager DOM element Add or Remove event function EventManager () {///Add event//odomelement:dom elements, such as buttons, text, document, etc. oeventtype: Events Name (such as: Click, if it is IE browser, automatically convert click to onclick); Ofunc: Event-triggered function names This.addevent = functions (Odomelement, Oeventtype,
    Ofunc) {//ie if (odomelement.attachevent) {odomelement.attachevent ("on" + Oeventtype, Ofunc); }//ff,opera,safari et else if (odomelement.addeventlistener) {Odomelement.addeventlistener (Oeventtype, OFunc
    , false);
    }//Other else {odomelement["on" + oeventtype] = Ofunc; } this.removeevent = function (Odomelement, Oeventtype, Ofunc) {//ie if (odomelement.detachevent) {O
    Domelement.detachevent ("on" + Oeventtype, Ofunc);  }//ff,opera,safari et else if (odomelement.removeeventlistener) {Odomelement.removeeventlistener (OEventType, Ofunc, FALSE);
    }//Other else {odomelement["on" + oeventtype] = null;

 }
  }
}

As the annotation writes, to register DOM element events, use Eventutil.addevent (DOM elements, event names, event-triggered function names), and you can write this as you remove them:eventutil.removeevent (DOM element, event name, Event-triggered function name), This is a digression, do not say.

The above is the entire content of this article, I hope that through this article we know more about JavaScript this keyword, we common progress.

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.