在面向对象的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