JSPrototype modification and rewriting
There are two ways to modify the js prototype:
1. In the original prototypeAddproperties and methodsto the object: 12
function Person(){ } Person.prototype.name="Mike"; Person.prototype.sayName=function(){ console.log(this.name); } var person= new Person(); person.sayName(); //Mike123456789
2. Override or overwrite the prototype object: 12
function Person(){ } Person.prototype={ "name":"Mike", sayName:function(){ console.log(this.name); } } var person=new Person(); person.sayName(); //Mike1234567891011
Next let’s look at a question: (This question also explains the difference between adding properties and methods directly to the prototype object and overriding or overwriting the prototype object.) 12
function Person(){ } function Animal(){ } var person=new Person(); var animal=new Animal(); Person.prototype={ "name":"Mike", sayName:function(){ console.log(this.name); } } Animal.prototype.name="animal"; Animal.prototype.sayName=function(){ console.log(this.name); } person.sayName(); //error person.sayName is not a function animal.sayName();//animal1234567891011121314151617181920 分析:12 function Person(){ } function Animal(){ } var person=new Person(); var animal=new Animal(); console.log(person. proto ===Person.prototype); //true console.log(animal.proto===Animal.prototype); //true Person.prototype={ "name":"Mike", sayName:function(){ console.log(this.name); } } Animal.prototype.name="animal"; Animal.prototype.sayName=function(){ console.log(this.name); } console.log(person.proto===Person.prototype); //false console.log(animal.proto===Animal.prototype); //true person.sayName(); //error person.sayName is not a function animal.sayName();//animal
Above This is a JS rewriting prototype object that I compiled for you. I hope it will be helpful to you in the future.
Related articles:
Detailed explanation of rewriting and overloading techniques of js methods
Focus on analysis of JavaScript rewriting alert () method skills
Focus on method rewriting in js inheritance
The above is the detailed content of Detailed explanation of JS rewriting prototype objects. For more information, please follow other related articles on the PHP Chinese website!