JavaScript学习笔记3-JavaScript中的继承2

本文介绍了JavaScript中实现对象继承的三种常见方法:使用apply方法、原型链方式及推荐的混合方式,并通过示例代码详细展示了每种继承模式的具体实现。

3) apply方法方式

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">

<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.sayWorld = function()
	{
		alert(this.password);
	}
}


var parent = new Parent("zhangsan");
var child = new Child("lisi", "123");

parent.sayHello();

child.sayHello();
child.sayWorld();


</script>

 </head>

 <body>
  
 </body>
</html>

4)原型链方式(无法给构造函数传参数)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">

<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.world = "world";
Child.prototype.sayWorld = function()
{
	alert(this.world);
}

var child = new Child();

child.sayHello();
child.sayWorld();

</script>

 </head>

 <body>
  
 </body>
</html>

5)混合方式(推荐)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">

<script type="text/javascript">

//使用混合方式实现对象继承(推荐)

function Parent(hello)
{
	this.hello = hello;
}

Parent.prototype.sayHello = function()
{
	alert(this.hello);
}

function Child(hello, world)
{
	Parent.call(this, hello);  //这句不会把sayHello方法设置到Child对象中,因此需要重新 <span style="font-family: Arial, Helvetica, sans-serif;">Child.prototype = new Parent();</span>

	this.world = world;
}

Child.prototype = new Parent();

Child.prototype.sayWorld = function()
{
	alert(this.world);
}

var child = new Child("hello", "world");

child.sayHello();
child.sayWorld();

</script>

 </head>

 <body>
  
 </body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值