SoFunction
Updated on 2025-02-28

Example analysis of usage of this in js

This article analyzes the usage of this in js. Share it for your reference. The specific analysis is as follows:

Example 1: The first method to call this - call it in function form. It represents the global object window

Copy the codeThe code is as follows:
<script type="text/javascript">
function t(){
alert(this);//Here this represents a window object.
}
t();
</script>

Example 2: The second method to call this - called in the form of object properties. It represents the object. Onclick is the attribute of the p element object in the instance
Copy the codeThe code is as follows:
<html>
<head>
<script type="text/javascript">
function t(){
 alert(this);
  = 'green';
}
= function(){
 ('eng').onclick = t;
}
</script>
</head>
<body>
<p >abcd</p>
</body>
</html>

Example 3: The third method to call this - called in the form of a constructor.
Copy the codeThe code is as follows:
<script type="text/javascript">
function dog(){
  = 4;
  = function(){
alert("Wangwang...");
 }
}
var wangcai = new dog();//How to create objects. new function name();
();
</script>

illustrate:
(1) If the dog() function is called directly instead of calling it in the way of creating an object, it is equivalent to the first type of call, that is, this represents the global object window.
(2) There is no concept of class in js, but there is a concept of object;
(3) The creation of objects can be created using var = objName{name:'abc',age:40}, or it can be created through constructors;
(4) What is a constructor: When an ordinary function is called in the form of "new function name()", this function acts as a constructor.

Example 4: The fourth method to call this - call and apply

Copy the codeThe code is as follows:
<html>
<head>
<script type="text/javascript">
= function(){
 var d = ('hi');
if(){//chrome and firefox
('click',function(){alert()},false);// In the w3c model, this points to the DOM object. The result is hi
 }else{// ie
('onclick',function(){alert()});//Eie8 and ie8 below, here this points to the global object window. The result is undefined
 }
}
</script>
</head>
<body>
<p >hello world</p>
</body>
</html>

I hope this article will be helpful to everyone's JavaScript programming.