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

首頁 > 語言 > JavaScript > 正文

JS實(shí)現(xiàn)面向?qū)ο罄^承的5種方式分析

2024-05-06 15:32:34
字體:
供稿:網(wǎng)友

本文實(shí)例講述了JS實(shí)現(xiàn)面向?qū)ο罄^承的5種方式。分享給大家供大家參考,具體如下:

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

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

實(shí)現(xiàn)原理:讓父類的構(gòu)造函數(shù)成為子類的方法,然后調(diào)用該子類的方法,通過this關(guān)鍵字給所有的屬性和方法賦值

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方法改變函數(shù)上下文實(shí)現(xiàn)繼承(該種方式不能繼承原型鏈,若想繼承原型鏈,則采用5混合模式)

實(shí)現(xiàn)原理:改變函數(shù)內(nèi)部的函數(shù)上下文this,使它指向傳入函數(shù)的具體對象

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方法改變函數(shù)上下文實(shí)現(xiàn)繼承(該種方式不能繼承原型鏈,若想繼承原型鏈,則采用5混合模式)

實(shí)現(xiàn)原理:改變函數(shù)內(nèi)部的函數(shù)上下文this,使它指向傳入函數(shù)的具體對象

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. 采用原型鏈的方式實(shí)現(xiàn)繼承

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

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. 采用混合模式實(shí)現(xiàn)繼承

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();            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 长海县| 张掖市| 噶尔县| 德令哈市| 蒲江县| 扬中市| 新郑市| 乐安县| 米易县| 冕宁县| 秦安县| 北海市| 县级市| 蓬溪县| 青岛市| 清水河县| 金坛市| 寻甸| 平舆县| 霍城县| 湘潭市| 新竹县| 青浦区| 苍梧县| 江永县| 堆龙德庆县| 犍为县| 沂源县| 衡阳县| 大田县| 通榆县| 东山县| 吉木萨尔县| 高唐县| 南汇区| 孝昌县| 个旧市| 长白| 和田市| 清河县| 伊金霍洛旗|