The difference between javascript prototype modification and rewriting (overwrite) Is that javascript prototype
Each JavaScript function has the prototype attribute (the javascript Object does not have this attribute). This attribute references an object, which is a prototype object. Javascript allows us to modify this prototype object. There are two ways to modify:
Method 1: Add attributes 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();//aty
Method 2: override (overwrite) the prototype object
function Person(){}Person.prototype = {add : function(){alert(this.name);},name : "aty"}var p2 = new Person();p2.add();//aty
We can see that both of the above methods can modify the prototype. What is the difference between them? Which method is recommended?
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 function
If you create an object first and then modify the prototype, if you use method 1, the created object can correctly access the modified prototype. If you use method 2, the created object cannot access the modified prototype. From this perspective, it is obvious that method 1 is better than method 2. Why?
Function Person () {} function Animal () {} var person = new Person (); var animal = new Animal (); alert (person. _ proto _ = Person. prototype); // truealert (animal. _ proto _ = Animal. prototype); // true // modify the prototype Person. prototype. say = function () {alert ("person");} // modify the prototype Animal. prototype = {say: function () {alert ("person") ;}} alert (person. _ proto _ = Person. prototype); // truealert (animal. _ proto _ = Animal. prototype); // false
Obviously, this is similar to "Modify reference" in java and "Modify Object pointed to by reference", and the effect is the same.