js中的prototype有什么作用?

来源:互联网 发布:java mvc模式的理解 编辑:程序博客网 时间:2024/05/07 04:37

1、

prototype对象是实现面向对象的一个重要机制。每个函数也是一个对象,它们对应的类就是

function,每个函数对象都具有一个子对象prototype。Prototype 表示了该函数的原型,

prototype表示了一个类的属性的集合。当通过new来生成一个类的对象时,prototype对象的属

性就会成为实例化对象的属性。

下面以一个例子来介绍prototype的应用,代码如下:

1
2
3
4
5
6
7
8
9
10
11
<script language="javascript">
//定义一个空类
function HelloClass(){
}
//对类的prototype对象进行修改,增加方法method
HelloClass.prototype.method=function(){
alert("prototype测试");
}
var obj=new HelloClass(); //创建类HelloClass的实例
obj.method(); //调用obj的method方法
</script>

当用new创建一个对象时,prototype对象的属性将自动赋给所创建的对象,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
<script language="javascript">
//定义一个只有一个属性的类
function HelloClass(){
this.name="javakc";
}
//使用函数的prototype属性给类定义新属性
HelloClass.prototype.showName=function(){
alert(this.name);
}
var obj=new HelloClass(); //创建类HelloClass的一个实例
//调用通过prototype原型对象定义的showName方法
obj.showName();
</script>

56

2、利用prototype实现继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script language="javascript">
function HelloClass(){
//构造方法
}
function HelloSubClass(){
//构造方法
}
HelloSubClass.prototype=HelloClass.prototype;
HelloSubClass.prototype.Propertys="name";
HelloSubClass.prototype.subMethods=function(){
//方法实现代码
alert("in Methods");
}
var obj=new HelloSubClass();
obj.subMethods();
</script>

在以上的代码中,首先是HelloSubClass具有了和HelloClass一样的prototype,如果不考

虑构造方法,则两个类是等价的。随后,又通过prototype给HelloSubClass赋予了额外的属性和方法

所以HelloSubClass是在HelloClass的基础上增加了新的属性和方法,从而实现了类的继承。

0 0
原创粉丝点击