“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

My understanding of constructors versus instantiation

When we're doing object-oriented programming, there's the process of abstraction => and then there's the process of instantiation like when we're abstracting a person, I know the basic information about a person. Name, age, sex,.... Wait, so we're abstracting first, and after we're done abstracting, we're instantiating.Copy the code

What is the relationship between constructors and instantiations?

Function Person(name,age,sex){this.name=name; this.age=age; this.sex=sex; This. Say =function(){console.log(" console.log ",name)}} per1.say(); // call //let per1=new Person(' SDN ',300,' female '); With this line above. We can conclude that the relationship between constructors and instance objects is that instance objects need to be created through constructors. Also: we know that the constructor of the instance object is the constructor. The above code does not change. Console. log(per1.constructor===Person) // returns true fully stating that the constructor of an instance object is a constructor.Copy the code

Whether per1.say is equal to per2.say

function Person(name,age,like) { this.name=name; this.age=age; this.like=like; This.say =function(){console.log(' I can skip dinner '); }} var per1=new Person(" Person ",300,' Person '); Var per2=new Person(' 1000 ','10000'); per1.say(); per2.say(); console.log( per1.say==per2.say ) //falseCopy the code

Per1. say does not equal the conclusion drawn by per2.say

Since console.log(per1.say==per2.say) //false we can draw a conclusion. Per1.say () and per2.say() do not call the same method, so are their contents equal? Console. log(per1.say()==per2.say()) //true indicates that the contents are equalCopy the code

Kangkang the following code appears the problem

function Person(name,age,like) { this.name=name; this.age=age; this.like=like; This.say =function(){console.log(' I can skip dinner '); }}; for (var index = 0; index < 100; Index++) {var per=new Person(" index ",300,' index '); per.say(); } this piece of code is that it opens up 100 Spaces in memory. Each space has a say method. But each say method is different. But the output is the same. Or the logic is the same. This creates a waste of space. So in a project, it's a waste of space. Can we optimize it?Copy the code

Optimize the code to solve the space waste

Function comSay(){// performs the same logic console.log(' I can skip meals ')}; function Person(name,age,like) { this.name=name; this.age=age; this.like=like; this.say=comSay; // Do not add parentheses}; Var per1=new Person(" Person ",300,' Person '); Var per2=new Person(' 1000 ','10000'); Console. log(per1.say==per2.say) //true then we save space. Every time it's called, it's the same method.Copy the code