javascript 继承实现

时间:2021-07-06 08:27:28

JavaScript高级程序设计读书笔记

这本书继承的实现列举了好几种,里面有两种是比较靠谱的。

1 组合继承

//父构造函数
function Super(name) {
this.name = name;
this.colors = ['black', 'red'];
}
Super.prototype.getName = function() {
return this.name;
} //子构造函数
function Sub(name, age) {
Super.call(this, name);
this.age = age;
}
//把Sub的原型修改为Super的实例,就能继承Super.prototype中的属性和方法了,
//这样存在的问题是:把name和colors属性也添加到Sub.prototype中了,这部分对实例是不可见的,
//因为调用new Sub()生成实例时,会把name和colors添加为实例属性
Sub.prototype = new Super();
Sub.prototype.getAge = function(){
return this.age;
}
//前面修改Sub.prototype时,导致Sub.prototype.constructor指向了Super,所以要修改回来
Sub.prototype.constructor = Sub; 
var ins1 = new Sub('mengxb', 28);

2 寄生组合式继承

function Object(o) {
function F() {};
F.prototype = o;
return new F();
}
function inheritPrototype(sub, super) {
var prototype = Object(super.prototype);
sub.prototype = prototype;
sub.prototype.construtor = sub;
} function Super(name) {
this.name = name;
this.colors = ['black', 'red'];
}
Super.prototype.getName = function() {
return this.name;
}
function Sub(name, age) {
Super.call(this, name);
this.age = age;
} inheritPrototype(Sub, Super);
Sub.prototype.getAge = function(){
return this.age;
}