資源描述:
《js原型鏈繼承方式的解析》由會員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、在面向?qū)ο笳Z言中,繼承有兩種形式:1.接口繼承;2.實現(xiàn)繼承。在js中只有實現(xiàn)繼承。利用原型鏈來實現(xiàn)繼承,基本思想是:利用原型讓一個引用類型繼承另一個引用類型的屬性和方法。代碼如下:Java代碼?1.??function?superClass?(){??2.????????this.property1?=?true;??3.????}????4.????superClass.prototype.method1?=?function?(){??5.????????console.log("supe
2、rClass?method1");??6.????}??7.????superClass.prototype.method2?=?function?(){??8.????????console.log("superClass?method2");??9.????}???functionsuperClass(){???????this.property1=true;???}????superClass.prototype.method1=function(){???????console.log(
3、"superClassmethod1");???}???superClass.prototype.method2=function(){???????console.log("superClassmethod2");???}Java代碼?1.????function?subClass?(){??2.????????this.property2?=?false;??3.????}??4.????subClass.prototype?=?new?superClass();??5.????subCla
4、ss.prototype.method1?=?function?(){??6.????????console.log("subClass?method1");??7.????}??8.????subClass.prototype.method3?=?function?()?{??9.????????console.log("subClass?method3");??10.????}?????functionsubClass(){???????this.property2=false;???}??
5、?subClass.prototype=newsuperClass();???subClass.prototype.method1=function(){???????console.log("subClassmethod1");???}???subClass.prototype.method3=function(){???????console.log("subClassmethod3");???}Java代碼?1.????var?superclass?=?new?superClass?();
6、??2.????superclass.method1();????????????????????????//superClass?method1??3.????superclass.method2();????????????????????????//superClass?method2??4.????var?subclass?=?new?subClass?();??5.????subclass.method1();??????????????????????????//subClass?m
7、ethod1??6.????subclass.method2();??????????????????????????//superClass?method2??1.????subclass.method3();??????????????????????????//subClass?method3??????varsuperclass=newsuperClass();???superclass.method1();???????????????????????//superClassmetho
8、d1???superclass.method2();???????????????????????//superClassmethod2???varsubclass=newsubClass();???subclass.method1();?????????????????????????//subClassmethod1???subclass.method2();?????????????????????????//superClassmethod2???subclass.method3();?