JS继承定义与使用方法简单示例

编程学习 2021-07-04 15:02www.dzhlxh.cn编程入门
这篇文章主要介绍了JS继承定义与使用方法,结合完整实例形式分析了JavaScript继承的基本定义、用法及操作注意事项,需要的朋友可以参考下

本文实例讲述了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代码运行工具:测试上述代码运行效果。

更多关于JavaScript相关内容可查看本站专题:《》、《》、《》、《》、《》及《》

希望本文所述对大家JavaScript程序设计有所帮助。

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板