这期内容当中小编将会给大家带来有关如何在JavaScript中继承定义,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
<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>
运行结果:
上述就是小编为大家分享的如何在JavaScript中继承定义了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。