前言:学习学习,有点懵
下面以一个例子来介绍prototype的应用,代码如下:
<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对象的属性将自动赋给所创建的对象,例如:
<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>
利用prototype实现继承
<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>