时间:2021-07-01 10:21:17 帮助过:5人阅读
2.代码如下:
[javascript] view plain copy
// supcalss
var parent = function(name,age){
this.name = name;
this.age = age;
}
parent.prototype.showProper = function()
{
console.log(this.name+":"+this.age);
}
var child = function(name,age){
parent.call(this,name,age);
}
// inheritance
child.prototype = Object.create(parent.prototype);
// child.prototype = new parent();
child.prototype.constructor = child;// rewrite function
child.prototype.showProper = function(){
console.log('I am '+this.name+":"+this.age);
}
var obj = new child('wozien','22');
obj.showProper();这样子类就是重写了父类的showProper方法了。其中Object.create(proto)函数是创建一个以proto对象为原型对象的对象,并且返回这个对象。
查找方法的顺序:obj -> child.prototype ->parent.prototype
3.注意的地方:在JS实现方法继承和重写的时候,或者在创建类方法的时候,都是在原型对象prototype上操作的,其他方式继承方法就不用考虑了。
相关文章:
JS中定义类的方法讲解
JavaScript的基本语法及变量讲解
js中一些基础常用的方法讲解
以上就是js继承中的方法重写重点讲解的详细内容,更多请关注Gxl网其它相关文章!