Introduction of the difference between JS constructor and prototype prototype

  • 2021-07-01 06:26:08
  • OfStack

The constructor method is easy to use, but there is a waste of memory

Functions allocated by prototyping are shared by all objects.

Attributes allocated by prototyping are independent.----If you don't modify attributes, they are shared

If we want all objects to use the same 11 functions, we'd better use prototyping to add functions, which saves memory.

Examples:

//----Constructor schema

Add an immutable attribute "type" (category) to the Cat object, and add a method eat (eat mouse). Then, the prototype object Cat becomes as follows:


<script>
function Cat(name, color) {
  this.name = name;
  this.color = color;
  this.type = " Cats ";
  this.eat = function () {
    alert(" Eat mice ");
  };
  }


// Generate an instance: 
var cat1 = new Cat(" Big hair ", " Yellow ");
var cat2 = new Cat("2 Hair ", " Black ");
alert(cat1.type);     //  Cats 
cat1.eat();    //  Eat mice  

alert(cat1.eat == cat2.eat); //false
</script>

That is, for every instance object, the type attribute and eat () method are all 1-mode 1-like contents, and every time an instance is generated, it must be repeated contents and occupy 1 more memory. This is neither environmentally friendly nor efficient.

//--Prototype mode

Javascript specifies that every constructor has one prototype attribute that points to another object. All properties and methods of this object will be inherited by the instance of the constructor.

This means that we can define those immutable properties and methods directly on the prototype object.


<script>
function Cat(name, color) {
  this.name = name;
  this.color = color;
  }


Cat.prototype.type = " Cats ";
Cat.prototype.eat = function () {
  alert(" Eat mice ")
};


// Generate an instance. 
var cat1 = new Cat(" Big hair ", " Yellow ");
var cat2 = new Cat("2 Hair ", " Black ");
alert(cat1.type); //  Cats 
cat1.eat();//  Eat mice 


alert(cat1.eat == cat2.eat);//trueF
</script>

At this time, the type attribute and eat () method of all instances are actually a memory address pointing to the prototype object, thus improving the running efficiency.


Related articles: