

JS原型的修改和重写
对于js原型的修改有两种方式:
1. 在原有的原型对象上添加属性和方法:12
function Person(){
}
Person.prototype.name="Mike";
Person.prototype.sayName=function(){
console.log(this.name);
} var person=
new
Person();
person.sayName(); //Mike1234567892. 重写或者说是覆盖原型对象:12
function Person(){
}
Person.prototype={ "name":"Mike",
sayName:function(){
console.log(this.name);
}
} var person=new Person();
person.sayName(); //Mike1234567891011接下来我们看一个问题:(这个问题也就解释了直接在原型对象上添加属性和方法和重写或者覆盖原型对象是有区别的。)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上面是我整理给大家的JS重写原型对象,希望今后会对大家有帮助。
相关文章:
js方法的重写和重载的技巧详解
重点分析JavaScript重写alert()方法的技巧
js继承中的方法重写重点讲解
