JavaScript中的子类和父类的继承

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值