实现继承方法的Javascript模拟

本文介绍了Javascript仿真实现继承的方法,供大家参考,具体分析如下:

我们都知道,我们只能用Javascript模拟OO中的类,这意味着Javascript中没有类继承,只能通过在原始对象中添加或重写属性来模拟实现。

首先,定义父类。


父类
Function ParentClass () {
this.classname =parentclass ;
this.auth =认证;
this.version =V1.0;
this.parentclassinfo =函数(){
返回this.classname + + this.auth + + this.version;
}
}


1。原型系统的实现:


子类
1,原型继承
函数的ChildClassByPrototype(){
this.date =2013-07-26 ;
this.classinfo =函数(){
返回this.parentclassinfo()++ this.date;
}
}
childclassbyprototype.prototype =新ParentClass();
无功cctest1 =新ChildClassByPrototype();
cctest1.parentclassinfo();
cctest1.classinfo();


这种方式很简单。只是指定父类的子类的实例的原型属性,然后子类可以使用父亲的方法和属性,这是用来寻找原型链的特点,如在cctest1.parentclassinfo案例(Javascript)的方法,首先将在ChildClassByPrototype的一个实例是parentclassinfo(搜索)的方法,没有阶级,所以找到ChildClassByPrototype.prototype物业,和原型属性的值是一个ParentClass的例子,这个例子parentclassinfo()方法,然后搜索完成后,调用成功。

二、实施实施:


2,应用继承
功能childclassbyapply(){
ParentClass.apply(这个新的数组());
/ / parentclass.apply(,{ });
this.date =2013-07-26 ;
this.classinfo =函数(){
返回this.parentclassinfo()++ this.date;
}
}


Javascript的应用可以理解为同一方法更换B方法,B方法本身的第一个参数的对象,第二个参数是一个数组,在传递到相应的一个方法的参数列表的数组值,如果参数是空的,没有参数,通过新(数组)的转移,{ }。

三,调用+原型实现:


3,调用+原型继承
函数的ChildClassByCall(){
parentclass.call(这个参数);
this.date =2013-07-26 ;
this.classinfo =函数(){
返回this.parentclassinfo()++ this.date;
}
}
childclassbycall.prototype =新ParentClass();


调用和应用程序具有相似的功能,也就是说,它们用A替换B方法,但是传递的参数是不同的。调用方法的第一个参数是B方法的对象,而后面的参数不是由数组包起来的,需要直接传递。这是因为调用方法只在不复制对象属性的情况下实现了方法的替换。

例如,如果父类有构造函数,每个方法都有它的应用环境:


函数的ParentClass(className,认证版){
this.classname =类名;
this.auth =认证;
this.version =版;
this.parentclassinfo =函数(){
返回this.classname + + this.auth + + this.version;
}
}


在这种情况下,原型是不适用的,可以选择应用程序或调用。


功能childclassbyapply(className,认证版){
ParentClass.apply(,{ className,认证版});
this.date =2013-07-26 ;
this.classinfo =函数(){
返回this.parentclassinfo()++ this.date;
}
}
功能childclassbycall(className,认证版){
parentclass.call(这个论点论据,{ 0 },{ 1 },{ 2 }参数);
/ / parentclass.call(这类名,认证版);
this.date =2013-07-26 ;
this.classinfo =函数(){
返回this.parentclassinfo()++ this.date;
}
}
childclassbycall.prototype =新ParentClass();


实例化:


无功cctest2 =新childclassbyapply(parentclass
无功cctest3 =新childclassbycall(parentclass


在申请和调用,我应该如何取出它在面向对象的继承,子类继承了父类,它应该是父类的类型。也就是说,childclassbycall和ChildClassByApply也应该parentclass类型,但是如果我们检测是因此,我们建议,电话+原型被用来模拟是继承。说继承眉目传情地图API是这样使用的。

希望本文能对大家的javascript程序设计有所帮助。