Understanding of JavaScript "this"

Posted by jpr on Sat, 02 May 2020 12:58:41 +0200

Text explanation:

1, Understanding of this:

This: it means "this". It's a pronoun. The meaning of pronoun is determined by the scene or situation.

You, me, him, this, that, are pronouns.
When someone says, "I'm eating", then who is this "I", we must see who said this sentence, who said it, who I am, that is, "I" will change according to the change of the speaker


2, Four situations of this in JavaScript

1. When this function is an event handler, this is the event source.
2. When this function is a constructor, this is an object out of new.
3. This is the object of this function.
4. When this function does not have an object, this is a window object


3, The transfer of this
When someone says, "I'm eating", then who is this "I", we must see who said this sentence, who said it, who I am, that is, "I" will change according to the change of the speaker

The meaning of this transfer is the same. Which object is this? You need to see the object of this function.

Code interpretation:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		
	</body>
</html>

<script type="text/javascript">
//this
//1. When this function is an event handler, this is the event source.
//document.getElementById("btn").onclick = function(){
//	this is btn
//}

//2. When this function is a constructor, this is an object out of new.
//function Person(name){
//	this.name = name; / / is the new object p1
//	this.eat = function(){
//		alert(this.name + "eating");
//	}
//}
//var p1 = new Person("Wang Yu");

//3. This is the object of this function.
//function Person(name){
//	this.name = name; / / is the new object p1
//	this.eat = function(){
//		alert(this.name + "eating"); / / who is this and who calls eat, or who is the object in front when calling eat
//	}
//}
//var p1 = new Person("Wang Yu");
//p1.eat(); / / when this sentence is executed, this in the eat function is p1
//var p2 = new Person("Wang Yudian");
//p2.eat(); / / when this sentence is executed, this in the eat function is p2

//4. When this function does not have an object, this is a window object.
     //In fact, global variables are properties of window objects.
function test(){
	console.log(this);//this is window
}

//test();//window objects can be omitted, so this sentence is equivalent to window.test();
//window.test();

//Global variables are properties of window objects
var t = "Wang Yu";

console.log(window.t);

var obj = {
	name:"Zhang Ding",
	sex:"male"
}

console.log(window.obj.name);

//Is this transfer a problem we will encounter?
//1) How to distinguish this
//  Be sure to see the membership object ()

//2) If you don't want to be tortured by this
//  You can choose the arrow function in ES6.

</script>


Topics: Javascript