ECMAScript中描述了原型链的概念,原型链是实现继承的主要方法。
实现原型链继承有一种基本模式
function SuperType () {
this.property = true;
} SuperType.prototype.getSuperValue = function () {
return this.property;
}; function SubType () {
this.subproperty = false;
}
//继承SuperType
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.getSubValue =function () {
return this.subproperty;
}; var instance = new SubType();
console.log(instance.getSuperValue()); //true
console.log(instance.getSubValue()); //false
原型链虽然可以实现继承,但是在对现有的原型进行修改时,原先的原型也会被修改。这也是原型链的问题。
构造函数
使用call或apply方法
function SuperType (name) {
this.name = name;
}
function SubType () {
//继承
SuperType.call(this, "Argu");
} var instance = new SubType();
console.log(instance.name);
在考虑到原型链和构造函数实现继承时的一些问题,用的比较多的是两种方式的组合形式
组合继承
function SuperMan (name) {
this.name = name;
this.friends = ["Bob","Angular","Y"];
} SuperMan.prototype.sayName = function () {
alert(this.name);
};
function SubMan (name, age) {
SuperMan.call(this, name); this.age = age;
}
SubMan.prototype = new SuperMan();
SubMan.prototype.constructor = SubMan;
SubMan.prototype.sayAge = function () {
alert(this.age);
};
var test1 =new SubMan("Nicur", "11");
test1.friends.push("Syze");
console.log(test1.friends); //["Bob", "Angular", "Y", "Syze"]
test1.sayName(); //Nicur
test1.sayAge(); //11 var test2 =new SubMan("Gina", "18");
console.log(test2.friends); //["Bob", "Angular", "Y"]
test2.sayName(); //Gina
test2.sayAge(); //18