JavaScript 中的继承(上)
作者:Flyingis继承是面向对象语言基本特征之一,通过继承可以将父类所具有的特性遗传到子类。ECMAScript中的继承不像Java、C++等语言那么明显,直接通过关键字来实现,通常它是通过模拟方式来实现继承功能的,并且实现方式有多种。
在继承中引入this关键字,使用构造器方法定义类来实现继承。一个构造器是一个函数,因此可以将父类的构造器作为子类的一个方法使用并进行调用。
<div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; font-size: 13px; width: 98%; background-color: rgb(238, 238, 238);"> http://www.agoit.com/Images/OutliningIndicators/ExpandedBlockStart.gif http://www.agoit.com/Images/OutliningIndicators/ContractedBlock.gif function ClassA(id)http://www.agoit.com/Images/dot.gif {
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif this .id = id;
http://www.agoit.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.agoit.com/Images/OutliningIndicators/ContractedSubBlock.gif this .sayId = function() http://www.agoit.com/Images/dot.gif{
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif alert(this.id);
http://www.agoit.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif };
http://www.agoit.com/Images/OutliningIndicators/ExpandedBlockEnd.gif}
http://www.agoit.com/Images/OutliningIndicators/None.gif
http://www.agoit.com/Images/OutliningIndicators/ExpandedBlockStart.gif http://www.agoit.com/Images/OutliningIndicators/ContractedBlock.gif function ClassB(id, name) http://www.agoit.com/Images/dot.gif {
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif this .newMethod = ClassA;
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif this .newMethod(id);
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif delete this.newMethod;
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif this.name= name;
http://www.agoit.com/Images/OutliningIndicators/ExpandedSubBlockStart.gifhttp://www.agoit.com/Images/OutliningIndicators/ContractedSubBlock.gif this.sayName= function()http://www.agoit.com/Images/dot.gif{
http://www.agoit.com/Images/OutliningIndicators/InBlock.gif alert(this.name);
http://www.agoit.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif };
http://www.agoit.com/Images/OutliningIndicators/ExpandedBlockEnd.gif}
页:
[1]