JavaScript
发布时间:2022-04-16 发布网站:大佬教程 code.js-code.com
大佬教程收集整理的这篇文章主要介绍了JavaScript模拟实现继承的方法,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
本文实例讲述了JavaScript模拟实现继承的方法。分享给大家供大家参考。具体分析如下:
我们都知道,在JavaScript中只能模拟实现OO中的"类",也就意味着,在JavaScript中没有类的继承。我们也只能通过在原对象里添加或改写属性来模拟实现。
先定义一个父类,
{
thi
s.className = "ParentClass";
thi
s.auth = "Auth";
thi
s.version = "V1.0";
thi
s.parentClassInfo = function ()
{
return thi
s.className + "\n" + thi
s.auth + "\n" + thi
s.version;
}
}
一、prototype 实现:
{
thi
s.date = "2013-07-26";
thi
s.classInfo = function ()
{
return thi
s.parentClassInfo() + "\n" + thi
s.date;
}
}
ChildClassByPrototype.prototype = new ParentClass(
);
var cctest1 = new ChildClassByPrototype(
);
cctest1.parentClassInfo(
);
cctest1.classInfo(
);
这种方式很简单,只需把父类的实例赋值给子类的prototype属性就行了,然后子类就可以使用父亲的方法和属性了。这里其实是用到了原型链向上查找的特性,比如这个例子中的 cctest1.parentClassInfo() 方法,JavaScript会先在ChildClassByPrototype的实例中查找是否有parentClassInfo()方法,子类中没有,所以继续查找ChildClassByPrototype.prototype属性,而其prototype属性的值是ParentClass的一个实例,该实例有parentClassInfo()方法,于是查找结束,调用成功。
二、apply 实现:
{
ParentClas
s.apply(this,new Array()
);
//ParentClas
s.apply(this,[]
);
thi
s.date = "2013-07-26";
thi
s.classInfo = function ()
{
return thi
s.parentClassInfo() + "\n" + thi
s.date;
}
}
JavaScript中的apply可以理解为用A方法替换B方法,第一个参数为B方法的对象本身,第二个参数为一个数组,该数组内的值为需要传递给A方法对应的参数列表,如果参数为空,即没有参数传递,可通过 new Array()、[] 来传递。
三、call + prototype 实现:
{
ParentClas
s.call(this,arguments
);
thi
s.date = "2013-07-26";
thi
s.classInfo = function ()
{
return thi
s.parentClassInfo() + "\n" + thi
s.date;
}
}
ChildClassByCal
l.prototype = new ParentClass(
);
call和apply作用类似,即都是用A方法替换B方法,只是传递的参数不一样,call方法的第一个参数为B方法的对象本身,后续的参数则不用Array包装,需直接依次进行传递。既然作用差不多,为何多了一句 原型赋值呢?这是因为call方法只实现了方法的替换而没有对对象属性进行复制操作。
每种方法都有其适用环境,比如,如果父类带有有参构造函数:
{
thi
s.className = className;
thi
s.auth = auth;
thi
s.version = version;
thi
s.parentClassInfo = function ()
{
return thi
s.className + "\n" + thi
s.auth + "\n" + thi
s.version;
}
}
这种情况下,prototype就不适用了,可选用apply或call;
{
ParentClas
s.apply(this,[className,version]
);
thi
s.date = "2013-07-26";
thi
s.classInfo = function ()
{
return thi
s.parentClassInfo() + "\n" + thi
s.date;
}
}
function ChildClassByCall(className,version)
{
ParentClas
s.call(this,arguments
[0],arguments[1],arguments[2]
);
//ParentClas
s.call(this,className,version
);
thi
s.date = "2013-07-26";
thi
s.classInfo = function ()
{
return thi
s.parentClassInfo() + "\n" + thi
s.date;
}
}
ChildClassByCal
l.prototype = new ParentClass(
);
实例化:
);
var cctest3 = new ChildClassByCall("ParentClass","V1.0"
);
在apply和call中,又该如何取舍呢?在OO的继承中,子类继承于父类,那么它应该也是父类的类型。即,ChildClassByCall、ChildClassByApply应该也是ParentClass类型,但我们用"instanceof"检测一下6.091499)::geographyR_668_11226@5@,通过apply继承的子类,并非ParentClass类型。所以,我们建议用call + prototype 来模拟实现继承。据说,Google Map API 的继承就是使用这种方式哟。
希望本文所述对大家的javascript程序设计有所帮助。
大佬总结
以上是大佬教程为你收集整理的JavaScript模拟实现继承的方法全部内容,希望文章能够帮你解决JavaScript模拟实现继承的方法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。