javascript学习五

<script type="text/javascript">
	//使用call实现继承
	function parent(username){
		this.username=username;
		this.sayHello=function(){
			alert(this.username);
		}
	}
	
	function child(username,password){
		parent.call(this,username);
		this.password=password;
		this.sayWord=function(){
			alert(this.password);
		}
	}
	
	var p=new parent("hello");
	var c=new child("word","123");
	
	p.sayHello();
	
	c.sayHello();
	c.sayWord();
</script>

 apply方法方式:

<script type="text/javascript">
	//apply方法实现对象继承
	function parent(username){
		this.username=username;
		this.sayHello=function(){
			alert(this.username);
		}
	}
	
	function child(username,password){
		parent.apply(this,new Array(username));
		this.password=password;
		this.sayWord=function(){
			alert(this.password);
		}
	}
	
	var p=new parent("hello");
	var c=new child("word","123");
	
	p.sayHello();
	c.sayHello();
	c.sayWord();
</script>

 原型链方式:无法给构造函数传递参数

<script type="text/javascript">
	//使用原型链(prototype chain)实现对象的继承
	function parent(){}
	parent.prototype.hello="hello";
	parent.prototype.sayHello=function(){
		alert(this.hello);
	}
	
	function child(){}
	child.prototype=new parent();
	child.prototype.word="word";
	child.prototype.sayWord=function(){
		alert(this.word);
	}
	
	var p=new parent();
	var c=new child();
	p.sayHello();
	c.sayHello();
	c.sayWord();
</script>

 混合方式:(推荐使用)

<script type="text/javascript">
	//使用混合方式实现对象的继承
	function parent(hello){
		this.hello=hello;
	}
	parent.prototype.sayHello=function(){
		alert(this.hello);
	}
	
	function child(hello,word){
		//实现属性的继承
		parent.call(this,hello);
		this.word=word;
	}
	//实现方法的继承
	child.prototype=new parent();
	child.prototype.sayWord=function(){
		alert(this.word);
	}
	
	var p=new parent("hello");
	var c=new child("word","123");
	
	p.sayHello();
	c.sayHello();
	c.sayWord();
</script>

 学到这里,javascript的核心应该已经学完了,可是自己感觉没什么进步,不知道大家是怎么在学习啊,希望大家能指教指教小弟。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值