国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

JS實現面向對象繼承的5種方式分析

2024-05-06 16:45:17
字體:
來源:轉載
供稿:網友

本文實例講述了JS實現面向對象繼承的5種方式。分享給大家供大家參考,具體如下:

js是門靈活的語言,實現一種功能往往有多種做法,ECMAScript沒有明確的繼承機制,而是通過模仿實現的,根據js語言的本身的特性,js實現繼承有以下通用的幾種方式

1. 使用對象冒充實現繼承(該種實現方式可以實現多繼承)

實現原理:讓父類的構造函數成為子類的方法,然后調用該子類的方法,通過this關鍵字給所有的屬性和方法賦值

function Parent(firstname){  this.fname=firstname;  this.age=40;  this.sayAge=function()  {    console.log(this.age);  }}function Child(firstname){  this.parent=Parent;  this.parent(firstname);  delete this.parent;  this.saySomeThing=function()  {    console.log(this.fname);    this.sayAge();  }}var mychild=new Child("李");mychild.saySomeThing();

2. 采用call方法改變函數上下文實現繼承(該種方式不能繼承原型鏈,若想繼承原型鏈,則采用5混合模式)

實現原理:改變函數內部的函數上下文this,使它指向傳入函數的具體對象

function Parent(firstname){  this.fname=firstname;  this.age=40;  this.sayAge=function()  {    console.log(this.age);  }}function Child(firstname){  this.saySomeThing=function()  {    console.log(this.fname);    this.sayAge();  }  this.getName=function()  {    return firstname;  }}var child=new Child("張");Parent.call(child,child.getName());child.saySomeThing();

3. 采用Apply方法改變函數上下文實現繼承(該種方式不能繼承原型鏈,若想繼承原型鏈,則采用5混合模式)

實現原理:改變函數內部的函數上下文this,使它指向傳入函數的具體對象

function Parent(firstname){  this.fname=firstname;  this.age=40;  this.sayAge=function()  {    console.log(this.age);  }}function Child(firstname){  this.saySomeThing=function()  {    console.log(this.fname);    this.sayAge();  }  this.getName=function()  {    return firstname;  }}var child=new Child("張");Parent.apply(child,[child.getName()]);child.saySomeThing();

4. 采用原型鏈的方式實現繼承

實現原理:使子類原型對象指向父類的實例以實現繼承,即重寫類的原型,弊端是不能直接實現多繼承

function Parent(){  this.sayAge=function()  {    console.log(this.age);  }}function Child(firstname){  this.fname=firstname;  this.age=40;  this.saySomeThing=function()  {    console.log(this.fname);    this.sayAge();  }}Child.prototype=new Parent();var child=new Child("張");child.saySomeThing();

5. 采用混合模式實現繼承

function Parent(){  this.sayAge=function()  {    console.log(this.age);  }}Parent.prototype.sayParent=function(){  alert("this is parentmethod!!!");}function Child(firstname){  Parent.call(this);  this.fname=firstname;  this.age=40;  this.saySomeThing=function()  {    console.log(this.fname);    this.sayAge();  }}Child.prototype=new Parent();var child=new Child("張");child.saySomeThing();child.sayParent();

 

希望本文所述對大家JavaScript程序設計有所幫助。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 利川市| 鹤岗市| 宜丰县| 密云县| 吴川市| 衡山县| 宁乡县| 高州市| 玉门市| 新龙县| 衡南县| 台东县| 临江市| 沁阳市| 石楼县| 黑龙江省| 深泽县| 金溪县| 长海县| 姜堰市| 宜州市| 池州市| 禹城市| 南丰县| 桃江县| 阿图什市| 北辰区| 临武县| 梁山县| 宿松县| 安丘市| 瑞丽市| 高州市| 城步| 千阳县| 清镇市| 云林县| 深水埗区| 威宁| 民县| 迁西县|