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

首頁 > 編程 > JavaScript > 正文

js繼承實現方法詳解

2019-11-19 18:26:19
字體:
來源:轉載
供稿:網友

本文實例講述了js繼承實現方法。分享給大家供大家參考,具體如下:

var animal=function(name){ //構造函數  this.name=name;  this.sayhello=function(){  alert("hi我是"+this.name);  };}animal.prototype.shout=function(){ //prototype主要作用:給類增加一個新的屬性或函數  alert(this.name+"正在叫!");};animal.prototype.game=function(){  alert(this.name+"正在玩耍!");};var dog=new animal("小黑");  //實例化dog.sayhello();dog.shout();dog.game();

一、原型繼承

var animal=function(name){  this.name=name;  this.sayhello=function(){  alert("hi我是"+this.name);  };}animal.prototype.shout=function(){  alert(this.name+"正在叫!");};animal.prototype.game=function(){  alert(this.name+"正在玩耍!");};var Dog=function(name){  this.name=name;  this.shout=function(){   //重寫父類的函數  alert(this.name+"汪汪叫!");  }}Dog.prototype=Cat.prototype=new animal();var dog=new Dog("小黑");dog.sayhello();dog.shout();dog.game();var cat=new Cat("小白");cat.sayhello();cat.shout();cat.game();

animal是父類(或超類),要繼承于誰,誰就是父類(超類)

改進:專門寫個函數,用來實現繼承

var animal=function(name){  this.name=name;  this.sayhello=function(){  alert("hi我是"+this.name);  };}Function.prototype.extends=function(superclass){      //extends是保留關鍵字,不能拿出來單獨使用,如var extends=function(){},而這里可以使用是因為他做為函數的屬性添加上去  this.prototype=new superclass();};animal.prototype.shout=function(){  alert(this.name+"正在叫!");};animal.prototype.game=function(){  alert(this.name+"正在玩耍!");};var Dog=function(name){  this.name=name;  this.shout=function(){  alert(this.name+"汪汪叫!");  }}Dog.extends(animal);var dog=new Dog("小黑");dog.sayhello();dog.shout();dog.game();var dog=new Dog("小白");dog.sayhello();dog.shout();dog.game();

二、call,apply繼承(不完全繼承)

var animal=function(name){  this.name=name;  this.sayhello=function(){  alert("hi我是"+this.name);  };}animal.prototype.shout=function(){  alert(this.name+"正在叫!");};animal.prototype.game=function(){  alert(this.name+"正在玩耍!");};var Dog=function(name){  animal.call(this,name);}var dog=new Dog("小黑");dog.sayhello();dog.shout();dog.game();

輸出:hi我是小黑

TypeError: dog.shout is not a function

通過call(apply)的方式,只能改變其this指向,通過prototype添加進去的方法,他是無法直接繼承的

總結:call,apply這種方式的繼承適用于沒有prototype的類或者不需要繼承prototype所添加屬性或函數的類,因為call和apply函數只是實現了方法的替換,而沒有對對象的屬性和函數進行復制操作

原型繼承,則可以繼承所有的屬性和函數

繼承的屬性,只有刪除原有屬性,才會輸出繼承的屬性

更多關于JavaScript相關內容可查看本站專題:《javascript面向對象入門教程》、《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阜阳市| 台江县| 大足县| 永仁县| 商南县| 石渠县| 洞口县| 盱眙县| 方城县| 松桃| 泰来县| 讷河市| 长春市| 乌审旗| 四子王旗| 桐庐县| 木兰县| 基隆市| 勐海县| 胶南市| 清徐县| 曲周县| 信阳市| 博爱县| 清水河县| 福安市| 荃湾区| 西青区| 灵石县| 房产| 洪洞县| 都兰县| 湟源县| 大埔区| 丰都县| 大同县| 富裕县| 进贤县| 德清县| 卫辉市| 四会市|