Javascript 类的继承

<!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" οnclick="show(1)">animalname</button>
<button id="button2" οnclick="show(2)">peoplename</button>
<button id="button3" οnclick="show(3)">catname</button>
<button id="button4" οnclick="show(4)">peopleintroduction</button>
<button id="button5" οnclick="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的使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值