JavaScript不支接直持继承机制.但可用其它方法代替.
本例使用两种方法实现继承.
Person类为父类,Student使用一种方法,Worker使用另一种方法.
<!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>
<script>
function Person()
{
var name;
this.setName = function(str){this.name = str;}
this.getName = function(){return this.name;}
}
//方法一 :在子类中添加一个任意的prototype指向父类.并调用其构造方法.
function Student()
{
//下面的Super不是JavaScript关键字,可以用其它非JavaScript关键字代替.
//比如:this.Super也可写成this.abc,this.Super()也可写成this.abc();
//为了避免在调用this.Super();时把子类原本存在的Property覆盖掉,所以
//下面这两句应该放在子类函数内部的最开头.
this.Super = Person;
this.Super();
var interest;
this.setInterest = function(str){this.interest = str;}
this.getInterest = function(){return this.interest;}
}
var stu1 = new Student();
stu1.setName("tyweber");
document.writeln("name of stu1:"+stu1.getName());
stu1.setInterest("play basketball");
document.writeln("interest of stu1:"+stu1.getInterest());
//方法二:创建一个工具函数,参数为父类对象和子类对象.
//并把父类对象的每个prototype添加到子类对象中(prototype必须是子类
//中不存在的)
function createInheritance(parent,child)
{
for(var property in parent)
{
if (!child[property])
{
child[property] = parent[property];
}
}
}
function Worker()
{
//在调用子类时,调用createInheritance函数,为子类添加父类的prototype.
createInheritance(new Person(),this);
var typeOfWork;
this.setTypeOfWork = function(str){this.typeOfWork = str;}
this.getTypeOfWork = function(){return this.typeOfWork;}
}
var worker1 = new Worker();
worker1.setName("zouyong");
document.writeln("name of worker1:"+worker1.getName());
worker1.setTypeOfWork("programer");
document.writeln("typeOfWork of worker1:"+worker1.getTypeOfWork());
</script>
</head>
<body>
</body>
</html>
浙公网安备 33010602011771号