《JavaScript学习笔记》:继承
继承在Java中直接用关键字extends即可完成,以下就是Java中一个关于继承的例子。
先有一个Person类,Person类中有两个属性:name、age;有两个方法:showName()、showAge();
然后有一个Teacher类,它是继承Person的,并且另外有一个title属性和一个showTitle()方法。
class Person{
public String name;
public int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public showName(){
system.out.println(name);
}
public showAge(){
system.out.println(age);
}
}
class Teacher extends Person{
public String title;
public Teacher(String name,int age,String title){
super(name,age); //调用父类的构造函数
this.title=title;
}
public showTitle(){
system.out.println(title);
}
}
继承在java中直接使用extends来实现即可获取父类非private的属性和方法。
而在Javascript中,继承就并不如用一个关键字即可解决,下面我们也以Person和Teacher来进行举例来说明,看看JavaScript中是如何来实现继承的。
Person类的代码如下,也是有两个属性和两个方法
// JavaScript Document
function Person(name,age)
{
this.name=name;
this.age=age;
};
Person.prototype.showName=function()
{
alert(this.name);
};
Person.prototype.showAge=function()
{
alert(this.age);
};
在JavaScript中Teacher类的继承是将属性和方法分成两部分来做的,在构造函数中通过调用Person.call(this,….);具体代码如下:
注意第一个参数是this关键字
// JavaScript Document
function Teacher(name,age,title)
{
Person.call(this,name,age);
this.title=title;
};
而如何使得Teacher得到其父类Person的函数了。
方法有两种
1、方法一:直接将Person.prototype给Teacher.prototype
Teacher.prototype=Person.prototype;
但是,这种方法的缺点是:我们后面在Teacher中添加的方法也同时添加到Person上面去了,原因是Teacher.prototype和Person.prototype指向同一个东西(用C语言的话说就是指向同一个地址)。
测试代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script src="Person.js"></script>
<script>
function Teacher(name,age,title)
{
Person.call(this,name,age);
this.title=title;
};
Teacher.prototype=Person.prototype;
//为Teacher类添加自己的方法
Teacher.prototype.showTitle=function()
{
alert(this.title);
};
alert(new Person('hao',34).showTitle);//结果是:Person对象中也有showTtitle方法,也就是引用的关系了,即Teacher.prototype=Person.prototype;不是复制,而是一种引用
</script>
</head>
<body>
</body>
</html>
运行上面的程序,会发现Person类也是具有title方法的,原因在上面已经解释过了,因此,我们一般不会采用这种方法。一般使用下面即将要介绍的这种方法来实现继承父类的方法。
2、方法二:通过遍历复制的方式将父类的每个方法复制给子类
这种方法Teacher类的方法和Person类的方法就是独立的,并不是指向同一个。
for(var i in Person.prototype)
{
Teacher.prototype[i] = Person.prototype[i];
}
因此,用这种方法之后,我们为Teacher添加的方法就只为Teacher类添加了方法,而并没有为Person添加方法。
最后,Teacher类的完成代码如下:
// JavaScript Document
function Teacher(name,age,title)
{
Person.call(this,name,age);
this.title=title;
};
Teacher.prototype=Person.prototype;
Teacher.prototype.showTitle=function()
{
alert(this.title);
};
以上就是关于JavaScript的继承,仔细想想,发现和Java中的继承的思想也差不多。