JS中的类和继承的实现

类:

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值