With artificial mirror, know the gain and loss, it seems that this sentence is very reasonable.
Demo 1:
If this is a global function, this is the Window object, and the various properties or methods defined in the function can be accessed outside of the function, provided that the function needs to be invoked.
Copy Code code as follows:
<script type= "Text/javascript" >
Use this in function
function A () {
if (this = = window) {
Alert ("This = = Window");
This.fielda = "I ' m a field";
This.methoda = function () {
Alert ("I ' m a function");
}
}
}
A (); If you do not call the A method, the properties defined inside will not get
alert (Window.fielda);
MethodA ();
</script>
Demo 2:
If you instantiate an object by using new, this is not equal to the Window object, this points to an instance of function a
Copy Code code as follows:
<script type= "Text/javascript" >
Use this second in function
function A () {
if (this = = window) {
Alert ("This = = Window");
}
else {
Alert ("This!= window");
}
This.fielda = "I ' m a field";
}
var B = new A ();
alert (B.fielda);
</script>
Demo 3:
Using the prototype extension method, you can use this to obtain an instance of the source object, which cannot be obtained by the prototype chain
Copy Code code as follows:
<script type= "Text/javascript" >
Use this third in function
function A () {
This.fielda = "I ' m a field";
var Privatefielda = "I ' m a var";
}
A.prototype.extendmethod = function (str) {
Alert (str + ":" + This.fielda);
alert (Privatefielda); Error
};
var B = new A ();
B.extendmethod ("from prototype");
</script>
Demo 4:
Whether it's directly referencing a function or instantiating a function, this in the closure function that it returns is pointing to Window
Copy Code code as follows:
<script type= "Text/javascript" >
Use this four in a function
function A () {
Alert (this = = window);
var that = this;
var func = function () {
Alert (this = = window);
alert (that);
};
return func;
}
var B = A ();
b ();
var C = new A ();
C ();
</script>
Demo 5:
Use this in HTML, which typically represents the element itself
Copy Code code as follows:
<div onclick= "Test (This)" id= "div" >click me</div>
<script type= "Text/javascript" >
function test (obj) {
alert (obj);
}
</script>
Demo 6:
Register the event under IE and Firefox (Chrome), this points to the window and the element itself, respectively.
Copy Code code as follows:
<div id= "Div" >click me</div>
<script type= "Text/javascript" >
var div = document.getElementById ("div");
if (div.attachevent) {
Div.attachevent ("onclick", function () {
Alert (this = = window);
var e = event;
Alert (E.srcelement = = this);
});
}
if (Div.addeventlistener) {
Div.addeventlistener ("click", Function (e) {
Alert (this = = window);
e = e;
Alert (E.target = = this);
}, False);
}
</script>
The above is my summary of this different scenario in JavaScript, there may be other situations, and later found will add in.