SoFunction
Updated on 2025-04-10

Analysis of this instance in JavaScript

Taking people as a mirror can tell gains and losses, it seems that this sentence makes sense.

Demo 1 :
If it is a global function, this is equivalent to a window object. Various properties or methods defined in the function can be accessed outside the function, provided that this function needs to be called.

Copy the codeThe code is as follows:

<script type="text/javascript">
//Use this in function
function a() {
if (this == window) {
alert("this == window");
= "I'm a field";
= function() {
alert("I'm a function ");
}
}
}
a(); //If the method a is not called, the attributes defined in it will not be retrieved
alert();
methodA();
</script>

Demo 2 :
If you use new to instantiate an object, this does not equal window object, this points to an instance of function a
Copy the codeThe code is as follows:

<script type="text/javascript">
//Use this second in function
function a() {
if (this == window) {
alert("this == window");
}
else {
alert("this != window");
}
= "I'm a field";
}
var b = new a();
alert();
</script>

Demo 3 :
Use the prototype extension method to get an instance of the source object using this, and the private fields cannot be obtained through the prototype chain
Copy the codeThe code is as follows:

<script type="text/javascript">
//Use this third in function
function a() {
= "I'm a field";
var privateFieldA = "I'm a var";
}
= function(str) {
alert(str + " : " + );
alert(privateFieldA); //Error
};
var b = new a();
("From prototype");
</script>

Demo 4 :
Whether it is referring to the function directly or instantiating a function, this in the closure function it returns points to the window
Copy the codeThe code is as follows:

<script type="text/javascript">
//Use this fourth in 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 :
Using this in HTML generally represents the element itself
Copy the codeThe code is as follows:

<div onclick="test(this)" >Click Me</div>
<script type="text/javascript">
function test(obj) {
alert(obj);
}
</script>

Demo 6 :
Register events under IE and Firefox (Chrome), this points to window and element itself, respectively
Copy the codeThe code is as follows:

<div >Click Me</div>
<script type="text/javascript">
var div = ("div");
if () {
("onclick", function() {
alert(this == window);
var e = event;
alert( == this);
});
}
if () {
("click", function(e) {
alert(this == window);
e = e;
alert( == this);
}, false);
}
</script>

The above are the different application scenarios of this in JavaScript that I have summarized. There may be other situations that vary. I will add them if I find it later.