您的位置:首页 > Web前端 > JavaScript

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

2015-09-02 13:58 736 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: