JS继承

今天把代码写了,再议内容

<!DOCTYPE html>
<html>
<head>
	<title>JS的继承</title>
</head>
<body>
	<script type="text/javascript">
		//父类
		function Animal(name){
			this.name=name;
			this.sleep=function(){
				console.log(this.name+" sleeping!");
			}
		}
		Animal.prototype.eat = function(food) {
			// body...
			console.log(this.name+" is eating "+food);
		};

		//父类测试对象
		var dog=new Animal("dog");
		dog.sleep();
		dog.eat("shit");



		//===================继承方式==============
		//原型链
		function Cat(){
			// this.sleep=function(){
			// 	console.log("sleep");
			// }
		}
		Cat.prototype=new Animal();//这个必须写在子类方法前
		// Cat.prototype.say=function(){
		// 	console.log("Cat say: "+this.name);
		// }
		Cat.prototype.name="cat";
		Cat.prototype.say=function(){
			console.log("Cat say: "+this.name);
		}
		Cat.prototype.sleep=function(){
			console.log("sleep");
		}

		
		var cat=new Cat();
		console.log(cat.name);
		cat.say();
		cat.sleep();
		cat.eat("fish");



		//构造继承
		function Fish(name){
			Animal.call(this);
			this.name=name||"neemo";
			Fish.prototype.say=function(){
				console.log(this.name+" is speaking!");
			}
			this.speaking=function(){
				console.log("speaking!");
			}
		}
		var fish=new Fish();
		fish.sleep();
		fish.say();
		fish.speaking();
		//fish.eat("shit");不可以继承父类的原型方法
	

		//实例继承
		function Person(name){
			var instance=new Animal();
			instance.name=name||'Tom';
			// this.say=function(){
			// 	console.log(this.name+" is speaking!");
			// }无法实现

			return instance;
			
		}
		// Person.prototype.speaking=function(){
		// 	console.log(this.name);
		// }  这个也无法实现
		var person=new Person(person);
		console.log(person.name);
		person.eat("shit");
		//person.say();
		//person.speaking();
		console.log(person instanceof Animal);
		console.log(person instanceof Person);

		//拷贝继承
		function Man(name){
			var animal=new Animal();
			for(var p in animal){
				Man.prototype[p]=animal[p];
			}
			Man.prototype.name=name||"Tom";
		}

		var man=new Man();
		console.log(man.name);
		man.sleep();

		//组合继承
		function Woman(name){
			Animal.call(this);
			this.name=name||"Woman";
		}
		Woman.prototype=new Animal();

		var woman=new Woman();
		woman.eat("shit");

		//寄生组合继承
		function SB(name){
			Animal.call(this);
			this.name=name||"SB";
		}
		(function(){
			var SBDog=function(){};
			SBDog.prototype=Animal.prototype;
			SB.prototype=new SBDog();
		})();

		var sb=new SB();
		sb.eat("only shit!");

</script>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值