JS原型的修改和重写
对于js原型的修改有两种方式:
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重写原型对象的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号