Javascript 继承模式

本文详细介绍了JavaScript中继承的实现方式,并通过实例展示了如何在项目中利用继承提高代码重用性和维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在面向对象的JavaScript开发中使用继承可以提高代码重用性,javascript有多重方式可以实现继承,考虑代码的可维护性在项目中应该保持代码风格的一致性,下面是JavaScript中继承的实现方式之一:

辅助对象:

var global = window;

(function(ns,undefined){
		  
	//辅助对象:
	var Class = {
		
		extends: function(SubClass, SuperClass){
			
			var F = function() {};
			F.prototype = SuperClass.prototype;
			SubClass.prototype = new F();
			SubClass.prototype.constructor = SubClass;
			
			SubClass.base = SuperClass.prototype;
			if(SuperClass.prototype.constructor == Object.prototype.constructor) {
				SuperClass.prototype.constructor = SuperClass;
			}
		  
		}
	}
	
	global.Class = Class;
}(global, undefined));

 继承模式:

function Person(name){
	this.name = name;
}

Person.prototype = {
	
	getName: function(){
		console.log("Person.prototype.getName")
	},
	
	say: function(){
		console.log("Person.prototype.say")
	}
};

function Employee(title, name){
	Employee.base.constructor.call(this, name);
	this.title = title;
}
Class.extends(Employee, Person);

//重写person.prototype.say
Employee.prototype.say = function(){
	Employee.base.say.call(this);//调用父类方法
	console.log("Employee.prototype.say");
};

Employee.prototype.getTitle = function(){
	console.log("Employee.prototype.getTitle")
};

 调用演示:

var e = new Employee("前端", "jser");
console.log(e.name)
console.log(e.title)
e.getName() 
e.getTitle()
e.say()

//运行结果:
//jser
//前端
//Person.prototype.getName
//Employee.prototype.getTitle
//Person.prototype.say
//Employee.prototype.say

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值