Each JavaScript function has a prototype attribute (the javascript object does not have this attribute). This attribute refers to an object, which is the prototype object. JavaScript allows us to modify this prototype object.
There are 2 ways to modify:
Method 1: Add properties or methods to the original prototype object
function Person(){}Person.prototype.add = function(){alert(this.name);};Person.prototype.name = "aty";var p1 = new Person();p1.add();//atyMethod 2: Rewrite (overwrite) the prototype object
function Person(){}Person.prototype = {add : function(){alert(this.name);},name : "aty"}var p2 = new Person();p2.add();//atyYou can see that the above two methods can modify the prototype, so what is the difference? Which method is the recommended method?
function Person(){}function Animal(){}var person = new Person();var animal = new Animal();// Modify the prototype Person.prototype.say = function(){alert("person");}// Modify the prototype Animal.prototype = {say : function(){alert("person");}}person.say();// personanimal.say();//Uncaught TypeError: undefined is not a functionIf you create an object first and then modify the prototype, then if you use Method 1, the object you have created can correctly access the modified prototype; if you use Method 2, the object you have created cannot access the modified prototype. From this perspective, obviously Method 1 is better than Method 2. Why is this happening?
function Person(){}function Animal(){}var person = new Person();var animal = new Animal();alert(person.__proto__ === Person.prototype);//truealert(animal.__proto__ === Animal.prototype);//true//Modify prototype Person.prototype.say = function(){alert("person");}//Modify prototype Animal.prototype = {say : function(){alert("person");}}alert(person.__proto__ === Person.prototype);//truealert(animal.__proto__ === Animal.prototype);//falseObviously, this is very similar to "modify reference" and "modify object pointed to by reference" in java, and the effect is the same.
The above detailed explanation of the difference between modification and rewriting (overwrite) of JavaScript 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.