类:
JS中的类就是函数,当把一个函数作为类的概念时,这个函数也叫做构造函数
如 Enemy.js文件:
// 类
function Enemy(name, level) {
//类的成员变量
this.name = name;
this.level = level;
}
//Enemy.prototype这个表我们又把他叫做类原型;
//类的成员函数
Enemy.prototype.attack_player = function() {
console.log("attack_player", this);
}
module.exports = Enemy;//导出类,外面可以用require来使用这个类
外部使用这个类:
var Enemy = require("./Enemy")
var e1 = new Enemy("e1", 1);
e1.attack_player();
var e2 = new Enemy("e2", 2);
e2.attack_player();
继承: 1.继承基类的成员变量,2.继承基类的成员函数(原型方法)
// step1: 继承基类的成员变量:
// 创建一个BossEnemy的构造函数;
function BossEnemy(name, level) {
// 通过调用基类的构造函数,来继承基类的成员变量
Enemy.call(this, name, level)
// 扩展自己的成员;
this.blood = 100;
}
// step2:继承基类的成员函数:
// 把Enemy里面所有的原型方法,都复制过来;
// BossEnemy.prototype = Enemy.prototype; // 不可以直接这样写;
// 写法1
BossEnemy.prototype = {};
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的__proto_: Enemy.prototype}
// 获取到原型以后,那么我就继承了 Enemy 的原型方法;
// 扩展自己的方法
BossEnemy.prototype.boss_attack = function() {
console.log("boss_attack");
}
var boss = new BossEnemy("通天教主", 10);
boss.boss_attack();
boss.attack_player();
//重写基类方法
BossEnemy.prototype.attack_player = function() {
Enemy.prototype.attack_player.call(this);
console.log("BossEnemy get name");
return this.name;
}
boss.attack_player();
// javascript 没有类,继承语法的, 使用new和this来模拟
// 可以写了一个继承函数;
// 这个Class函数,能帮我们得到新的类
function Class(class_desic) {
var new_class = function(name, level) {
if (class_desic.extend) { // 有基类
class_desic.extend.call(this, name, level);
}
if (class_desic.init) {
class_desic.init.call(this);
}
}
if (class_desic.extend) {
var a = function() {};
a.prototype = class_desic.extend.prototype;
//new_class.prototype.__proto__={__proto__:a.prototype表}
new_class.prototype = new a();
}
else {
new_class.prototype = {};
}
for(var i in class_desic) {
if (i == "extend") {
continue;
}
new_class.prototype[i] = class_desic[i];
}
return new_class;
}
var BossEnemy2 = Class({
// 定义写死的关键字 extend 是继承自那个基类
extend: Enemy, // 对象的名字
init: function(){
},
boss_attack: function() {
},
add_blood: function() {
console.log("add_blood", this);
},
});
var b2 = new BossEnemy2("boss2", 1111);
console.log(b2);
b2.add_blood();