最近总被人问到关于在js中如何实现继承。作为一个js苦手,虽然写了不少代码,但是还真没想过在js里,这个继承到底要怎么搞。趁着今天QA没有提bug,看了看«javascript高级程序设计»里关于继承的这一章。 看来看去,其实绝大部分还是在prototype和constructor上做文章,比如,最基本的继承:
// 父类
var fatherClass = function () {
this.name = 'father';
};
fatherClass.prototype.getName = function () {
return this.name
};
// 子类
var sonClass = function () {
this.name = 'son';
};
sonClass.prototype = new fatherClass();
这个时候,其实子类就已经继承了父类中的getName方法。其实说白了,继承无非就是prototype上方法的重复利用。
你说我把每个对象都单独定义一个getName行不行?
当然可以,无非就是代码难看点儿,不够优雅,可维护性差点儿罢了。
说到这个优雅,为了这两个字,多少程序员呕心沥血,创造了一种又一种的设计模式,开发框架,在社区里争来争去。
再说回来,其实在工作中对所谓的继承的使用,更实用的方式大概应该是这种:
// 父类
var fatherClass = function () {
this.name = 'father';
};
fatherClass.prototype.getName = function () {
return this.name
};
// 子类
var sonClass = function () {
this.name = 'son';
};
// 这里用了个Object.create方法
// 具体的实现应该就是将fatherClass.prototype的属性和方法复制出来,赋给另一个新创建的对象,然后返回新建的这个对象
sonClass.prototype = Object.create(fatherClass.prototype);
sonClass.prototype.constructor = sonClass;
不过话其实又说回来,工作了快三年了,用到继承的地方真是屈指可数啊…