The relationship between constructor, instance object, and prototype object in js

in conclusion:

Just like in a family, the father is the grandfather’s son, the child’s father, and the wife’s husband. The prototype object is also "multiple jobs".
If A comes from B new, we call A an instance of B. The implicit prototype object of A is equivalent to the explicit prototype object of B.
Below is a simple explanation with the following code and relationship diagram.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			function Mali(name, color) {
    
    
				this.name = name;
				this.color = color;
				this.eat = function(){
    
    
					alert('吃')
				}
			}
			Mali.prototype.jump = function() {
    
    
				alert('跳高高')
			}
			
			Object.prototype.run = function(){
    
    
				console.log('快跑')
			}
			
			var xh = new Mali("xh", 'red');
			var xl = new Mali("xl", 'green')

			console.log(xh)
			console.log(xl)
			xh.eat();
			xl.jump();
			xh.run();
			xh.hat();
		</script>
	</body>
</html>

Relationship diagram
relation chart
Because the two instance objects xh and xl are generated according to the constructor Mali, the implicit prototype object of xh and xl is equal to the display prototype object of Mali. xh._ _ proto __ are all equal to Mali.prototype. Just like a son calling his father's father grandfather, they are all the same person, called different.
And because Mali's prototype object (let's call it C for the time being) is the new Object object, so this object itself (C object) is also an instance object. (New ones are all instance objects) The implicit prototype of the C object is equivalent to the displayed prototype object of the Object (D object).
By default, the implicit object of Object is null.
xh.run(); Xiaohong wants to call the run method. Because she doesn't have it, she went to find her prototype object (C object). As a result, there was no C object, so she continued to look up, found D object, and found D The object has this method, so Xiaohong calls the run method.The route Xiao Hongxun takes in the process of the method she needs to call is called the prototype chain.

If there is an error, please feel free to correct it; if you have any questions, please leave a message for discussion.

Guess you like

Origin blog.csdn.net/xiaozuo144/article/details/109862906