JS繼承定義與使用方法簡單示例
本文實例講述了JS繼承定義與使用方法。分享給大家供大家參考,具體如下:
<script> function Enemy() { this.level = 50; console.log("Enemy constructor"); } Enemy.prototype.attack_play = function(){ console.log("attack_play"); }; Enemy.prototype.wudiai = 100; Enemy.wudiai = "1213"; Enemy.gongji = function(){ console.log("gongji asasasd "+ Enemy.wudiai); } function BossEnemy(){ Enemy.call(this); console.log("Boss constructor"); } // 寫法1 // BossEnemy.prototype = {constructor: BossEnemy,}; // for(var i in Enemy.prototype){ // BossEnemy.prototype[i] = Enemy.prototype[i]; // } // 寫法2 var a = function (){}; a.prototype = Enemy.prototype; BossEnemy.prototype = new a(); BossEnemy.prototype.boss_attack = function(){ console.log("boss_attack"); }; BossEnemy.staticFunc = function(){ console.log("staticFunc called!"); }; var bos = new BossEnemy(); bos.boss_attack(); bos.attack_play(); BossEnemy.staticFunc(); console.log("=========================="); BossEnemy.prototype.attack_play = function(){ Enemy.prototype.attack_play.call(this); console.log("BossEnemy attack play!"); } bos.attack_play(); console.log("*****************************"); // 寫法三 js6 class BingEnemy extends Enemy{ constructor(){ super(); this.flag = true; this.name = "通天教主"; this.level = 100; } static staticFunc(){ console.log("static func called!"); } get BingName(){ return this.name; } set BingName(value){ this.name = value; } }; BingEnemy.haha ="123"; let bing = new BingEnemy(); console.log(bing); BingEnemy.staticFunc(); bing.attack_play(); console.log(bing.BingName); bing.BingName = "jade"; console.log(bing.BingName); //console.log(BingEnemy.wudi); console.log("============================"); </script>
運行結果:
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
更多關于JavaScript相關內容可查看本站專題:《JavaScript常用函數(shù)技巧匯總》、《javascript面向對象入門教程》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數(shù)據(jù)結構與算法技巧總結》及《JavaScript數(shù)學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
javascript使用正則獲取url上的某個參數(shù)
使用indexOf取得?之后的參數(shù),以&使split進行分割成數(shù)組,下面展示了一個從url上獲取名為MenuCode參數(shù)的過程2014-09-09JS實現(xiàn)探測網(wǎng)站鏈接的方法【測試可用】
這篇文章主要介紹了JS實現(xiàn)探測網(wǎng)站鏈接的方法,通過網(wǎng)站返回錯誤響應觸發(fā)onerror時間來判斷網(wǎng)站鏈接的可用性,非常簡便實用,需要的朋友可以參考下2016-11-11實用的JS正則表達式(手機號碼/IP正則/郵編正則/電話等)
實用的JS正則表達式(手機號碼/IP正則/郵編正則/電話等),經(jīng)驗積累,感興趣的朋友可以了解下,一定會對你有幫助的2013-01-01