我们要定义一个名为com.levinzhang.Employee 的类,继承自com.levinzhang.Person,并要添加名为workExperience的属性、重写getName方法等功能:
dojo.declare("com.levinzhang.Employee", com.levinzhang.Person,{ workExperience:null, constructor: function(name,age,workExperience){ this.workExperience = workExperience; }, getWorkExperience:function(){ return this.workExperience; }, getName:function(){ return "Employee:"+this.name; }, getInput:function(){ return 5000; } });
在以上的代码中,我们定义的com.levinzhang.Employee继承了com.levinzhang.Person并添加了自定义的方法。测试代码如下:
var employee = new com.levinzhang.Employee("levin",30,4); alert(employee.getName());//将提示出Employee:levin alert(employee.getWorkExperience());//将提示出4 alert(employee.getAge());//将提示出30
可以看到在Employee的实例中,我们能够调用父类中定义的方法。而在类的constructor初始化方法中,我们并没有调用父类相关的方法,但是我们成功初始化了name和age两个属性,这是因为dojo会自动调用父类的初始化方法,完成继承要求的相关初始化工作。
example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>dojo定义对象-单继承</title>
<script type="text/javascript" src="js/dojo-release-1.11.2/dojo/dojo.js" djConfig="parseOnLoad: true"></script>
<script>
//定义srr
dojo.declare("com.srr.Miss", null, {
name: "srr",
age: "26",
staticInfo:{count:0},
constructor: function(name, age) {
this.name = name;
this.age = age;
++this.staticInfo.count;
},
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
});
//声明一个miss
var miss1 = new com.srr.Miss("沈荣荣1",22);
//alert(miss1.getName()+"---"+miss1.getAge()+"---;静态变量值="+miss1.staticInfo.count);
//声明一个miss
var miss2 = new com.srr.Miss("沈荣荣2",23);
//alert(miss2.getName()+"---"+miss2.getAge()+"---;静态变量值="+miss1.staticInfo.count);
//定义继承srr 的类daughter
dojo.declare("com.srr.miss.Daughter",com.srr.Miss,{
father:null,
constructor:function(name,age,father){
this.father=father;
},
getFather:function(){
return this.father;
},
getName:function(){
return "Daughter:"+this.name;
},
getInput:function(){
return 8888;
}
});
//生命继承类
var daughter = new com.srr.miss.Daughter("沐熙",2,"ygf");
alert("姓名:"+daughter.getName()+";年龄:"+daughter.getAge()+";爸爸:"+daughter.getFather());
</script>
</head>
<body>
</body>
</html>