JavaScript中的子类和父类的继承

来源:互联网 发布:杭州恩牛网络 上市 编辑:程序博客网 时间:2024/05/23 13:03

使用原型继承,中间使用临时对象作为Child的原型属性,临时对象的原型属性再指向同一个对象,这样当修改子类的原型属性,就不会影响到其他子类和父类。

function extend(Child, Parent){var F=function(){};//创建临时对象Child.prototype=Parent.prototype;//临时对象的原型属性指向同一个父类的原型Child.prototype=new F();//子类的原型对象指向临时对象Child.prototype.constructor==Child;//防止子类和父类的原型属性都指向同一个对象Child.base=Parent.prototype;//这句话不是很明白,如果有人看到,可以解释一下}function Parent(name){this.email='email@qq.com'this.getName=function(){return name;}this.setName=function(value){name=value;}}Parent.prototype.print=function(){alert('print!')};Parent.prototype.hello=function(){console.log(this.getName()+', Parent!');}function Child(name, age){Parent.apply(this,arguments);//调用父类的构造函数来继承父类的属性和方法this.age=age;}extend(Child, Parent);Child.prototype.hello=function(){console.log(this.getName()+", Child!");Parent.prototype.hello.apply(this, arguments);//调用父类的方法,这里并没有修改父类的方法}//子类的方法Child.prototype.doSomething=function(){console(this.age+", Child doSomething");}var p1=new Child('John', 24);p1.hello();//出现John, Child! 和 John, Parent!


原创粉丝点击