javascript prototype [note]

<!DOCTYPE HTML>

<html>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
	<title>Prototype</title>
</head>

<body>
	<div class="container"></div>
	
	<script type="text/javascript">

	function Animal(type){			// create a class
	    this.type = type;
	}

	Animal.prototype = {			// add attribute or methods to class by using .prototype

	    age : 0,					// add attribute

	    setAge : function(age) {	// add method
	    	this.age = age;
	    	console.log("Age is set to: " + this.age);
	    },


	    introduce : function(){
	    	console.log('This is ' + this.name);
	    }

	}



	function Cat(name){				// create a class
		this.name = name;
	};
	Cat.prototype = new Animal('Cat');  // add Animal's attributes and methods to Cat class
	var kate = new Cat('kate');		// create an instacne of Cat




	function Dog(name){
		this.name = name;
	};	
	Dog.prototype = new Animal('Dog');

	Dog.prototype.introduce = function(){  // overwrite Dog class' "introduce" function which cloned from Animal 
		console.log('wow ' + this.name);
	};



	var shiba = new Dog("shiba");		// create instacnes of Cat
	var hachi = new Dog("hachi");

	hachi.introduce = function(){       // overwrite object hachi's "introduce" function
		console.log('chi qiang');
	}


	console.log(shiba.type);	//  Dog
	kate.setAge(6);				//  Age is set to: 6 

	kate.introduce();			//	This is kate
	shiba.introduce();			//	wow shiba
	hachi.introduce();			//	chi qiang

	</script>

</body>

</html>

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值