JavaScript实现"继承"

实现方法:在javascript中没有继承的概念,ECMAScript中提出了原型链的概念,并将原型链作为实现继承的主要方式
基本思想:利用原型让一个自定义类继承另一个类的属性和方法
	//定义父类person
	function person(n,a,p){
		this.name=n;
		this.age=a;
		this.phone=p;
	}
	//父类方法
	person.prototype.sayHello=function(){
		alert(this.name+"向你问好");
	}
	//定义子类student
	function student(s){
		this.score=s;
	}
	//子类继承
	student.prototype=new person();
	//子类重写父类方法
	student.prototype.sayHello=function(){
		alert("学生"+this.name+"向你问好");
	}
	//声明子类独有的方法
	student.prototype.getDetials=function(){
		alert(this.name+"成绩"+this.score);
	}
	var s=new student();

       s.name="张无忌";
	s.age="28";
	s.phone="123456";
	s.score=100;
	s.sayHello();
	s.getDetials();

子类利用父类构造方法为属性赋值:

	function Person(n,a,p){
		this.name=n;
		this.age=a;
		this.phone=p;
	}
	Person.prototype.sayHello=function(){
	    alert(this.name+"向你问好!");
	}
	function Student(n,a,p,s){
		Person.call(this,n,a,p);//用Person来替换this(Student)
		//Person.call(this,n,a,p)==Person(n,a,p);
		this.score=s;}
	Student.prototype=new Person();
	Student.prototype.sayHello=function(){
		alert("学生"+this.name+"向你问好!");}
	Student.prototype.getDetials=function(){
	     alert(this.name+"的成绩是"+this.score);}
	var s=new Student("张无忌",28,"18638643721",100);
	s.sayHello();
	s.getDetials();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值