When we create an object with a constructor, its properties will be added to this. And the attributes added to this will not actually change with the entity, and at this time, our approach will appear inefficient. For example:
function her(){ this.name = 'Anna';}This means that every time we create an instance object with new her(), we will generate a brand new name attribute and have its own storage space in memory that belongs to the attribute. In fact, we can add the name attribute to the prototype, so that all instances can share this name attribute:
function her(){}her.prototype.name = 'Anna';In this way, when we use new her() to create an object, the name attribute is no longer a private property of the new object, but is added to the prototype of the object. Although this approach will be very efficient, it is also for the immutable properties in the instance object. This is certain. If you change this property, the attribute of all the created new objects will be changed. This is not what we want~~~. The public properties of an object are particularly suitable for this approach.
Here, let's improve a previous example:
function her(){};her.prototype.name = 'Anna';her.prototype.toString = function(){ return this.name;}function his(){}; his.prototype = new her(); his.prototype.constructor = his;his.prototype.sex = 'women';As you can see, we usually complete the construction of relevant inheritance before we expand the prototype object, otherwise the subsequent new attribute methods in his.prototype may erase the inherited things.
function child(f, m){ this.eat = f; this.don = m;}child.prototype = new his();child.prototype.constructor = child;child.prototype.name = 'Jok';child.prototype.fun = function(){ return this.eat + this.don}As you can see, the difference between calling toString() is actually just the small number of operations behind the scenes. The main difference is properties, the search work of methods will happen more in her.prototype.
The above javascript implementation method of migrating shared attributes to the prototype is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.