您的位置:首页 > Web前端 > JavaScript

Javascript 类的继承

2014-07-25 15:03 113 查看
<!DOCTYPE HTML>
<html>
<head>
<title>class in javascript</title>
<script>
var initializing=false;
function animal(){
if(!initializing){
this.init.apply(this,arguments)
}
/*this.name=name;*/
}
animal.prototype ={
/*to avoid people to init animal*/
init:function(name){
this.name=name;
},
getName: function(){
return this.name;
}
}

function people(name,age){
if(!initializing){
this.init.apply(this,arguments)
}
}
initializing=true;
people.prototype=new animal();
people.constructor=people;
initializing=false;
people.prototype.init=function(name,age){
this.name=name;
this.age=age;
}
people.prototype.getinfo= function(){
return "It's a people named "+this.name+", "+this.age;
}
people.prototype.constructor=people;
function cat(name,color){
this.name=name;
this.color=color;
}
cat.prototype=new animal();
cat.prototype.getinfo=function(){
return "It is a "+this.color+"cat,his name is "+ this.name;
}

var a=new animal("Join");
var b= new people("Kate",16);
var c = new cat("Allen","Red");

function show(id){
switch (id){
case 1:
result.innerHTML=a.getName();
break;
case 2:
result.innerHTML=b.getName();
break;
case 3:
result.innerHTML=c.getName();
break;
case 4:
result.innerHTML=b.getinfo();
break;
case 5:
result.innerHTML=c.getinfo();
break;
default:
;
}
}

</script>
</head>
<body>
<button id="button1" onclick="show(1)">animalname</button>
<button id="button2" onclick="show(2)">peoplename</button>
<button id="button3" onclick="show(3)">catname</button>
<button id="button4" onclick="show(4)">peopleintroduction</button>
<button id="button5" onclick="show(5)">catintroduction</button>
<span id="result"></span>
</body>
</html>


具体参考http://www.cnblogs.com/sanshi/archive/2009/07/08/1519036.html

其中将initializing这个全局变量去掉的jclass函数没有看懂。

另外,注意prototype apply的使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: