继承的方式
我们知道JavaScript是面向对象的脚本语言,那么既然是面向对象,继承一定是必不可少的了。JavaScript的核心是ECMAScript,JavaScript继承机制的实现其实就是ECMAScript继承机制的实现。ECMAScript 实现继承的方式不止一种。这是因为 JavaScript 中的继承机制并不是明确规定的,而是通过模仿实现的。这意味着所有的继承细节并非完全由解释程序处理。作为开发者,你有权决定最适用的继承方式。最原始的继承实现方式就是对象冒充,下面着重介绍该方法。
1) 对象冒充
对象冒充实现继承的核心其实依赖于在函数环境中使用 this 关键字。其原理如下:构造函数使用 this 关键字给所有属性和方法赋值(即采用类声明的构造函数方式)。因为构造函数只是一个函数,所以可使 ClassA 构造函数成为 ClassB 的方法,然后调用它。ClassB 就会收到 ClassA 的构造函数中定义的属性和方法。例如,用下面的方式定义 ClassA 和 ClassB:
<pre name="code" class="javascript"><!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(username)
{
this.username = username;
this.sayHello = function()
{
alert(this.username);
}
}
function Child(username, password)
{
//下面三行代码是最关键的代码
this.method = Parent;
this.method(username);
delete this.method;
//这种方式错误。因为Parent对象里的this只有new的时候才会产生
//即使加上new关键字也不行,因为调用的话 [new Parent(username)] Parent方法里的this 指的是Parent对象,并不是Child对象
Parent(username);
this.password = password;
this.sayWorld = function()
{
alert(this.password);
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi", "1234");
parent.sayHello();
child.sayHello();
child.sayWorld();
</script>
</head>
<body>
</body>
</html>
2) call方法方式。call方法是Function对象中的方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第2个参数开始,逐一赋值给函数中的参数。
<!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">
//继承的第二种实现方式,call方法方式,Function对象中的方法
function test(str, str2)
{
alert(this.name + ", " + str + ", " + str2);
}
var object = new Object();
object.name = "zhangsan";
//test.call相当于调用了test函数
test.call(object, "shengsiyuan", "hello"); //将object赋给了this
</script>
</head>
<body>
</body>
</html>
<!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">
//使用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.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>