function Fu(uname ,age ){
//1. Instance member
this.name =name ;
this.age =age;
this.sing=function(){
console.log("Eat watermelon")}}//2. Instantiate different objects
// Create an object when new and return the instance
let lj = new Fu('cole'.18);
let ll =new Fu('李路'.19);
// Call different instance objects with the same common method
lj.sing()
ll.sing()
// Constructor faults
// (1) There is a memory waste problem
// (2
Copy the code
‘// Solve the constructor waste memory problem
- 1: javaScript dictates that every constructor has a prototype property that points to the prototype object, so you just define the method to that prototype
- Prototype. Method name =function(){}
- For each instantiation object (e.g. Lj) the system adds its own __proto__ to our constructor prototype object (e.g. Fu.prototype).
- console.log(lj.proto === Fu.prototype); To true
- Note: Instantiate object (__proto__) constructor prototype object (prototype object)
- As shown in figure
-
Note: the __proto__ lookup mechanism first looks for sing in the instance object, and then looks for sing in the constructor prototype object
-
Note: __proto__ cannot be assigned only to the reference constructor prototype object
-
The prototype object has a constructor property that points to the constructor itself
-
Note: The constructor property (_proto) and the constructor property (prototype) refer to the constructor itself. Prototype ={constructor :Fu}. Prototype ={constructor :Fu}
-
Prototype chain diagram: below