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中一些基础常用的方法讲解
Copyright © 2019- yrkf.cn 版权所有
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务