码迷,mamicode.com
首页 > 其他好文 > 详细

prototype

时间:2018-08-31 19:19:40      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:类的继承   行修改   对象   创建   prot   table   实例化   keyword   www   

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的基础上增加了新的属性和方法,从而实现了类的继承。

prototype

标签:类的继承   行修改   对象   创建   prot   table   实例化   keyword   www   

原文地址:https://www.cnblogs.com/gy-dxj/p/9567143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!