使用原型继承,中间使用临时对象作为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!