js继承
主要有原型链、借助构造函数、组合继承、原型式继承、寄生式继承、寄生组合继承6种,但是由于原型链、构造函数、原型式继承、寄生继承都有一定的缺点,并不常用,故此不在赘述。
- 组合继承
function super(name) { this.name = name; this.colors = ["red","blue"]; } super.prototype.sayName = function(){ alert(this.name); }; function sub(name,age){ super.call(this,name); //属性继承 第二次调用super() this.age = age; } sub.prototype = new super(); //方法继承 第一次调用super() sub.prototype.sayAge = function(){ alert(this.age); }; var instance1 = new sub("Barney",32); instance1.colors.push("balck"); alert(instance1.colors);//red blue black instance1.sayName();//Barney instance1.sayAge();//32 var instance1 = new sub("Ted",33); alert(instance1.colors);//red blue instance1.sayName();//Ted instance1.sayAge();//33
如上所示,两个实例之间的白能量并没有互相影响,而且都可以使用super和sub中的方法,但是super()被调用了两次,显得有些多余,所以有了原型式继承
- 寄生组合继承
function inheritPrototype(subType,superType){ var prototype = Object(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; } function super (name){ this.name = name; this.colors = ["red","blue"]; } super.prototype.sayName = function(){ alert(this.name); }; function sub(name,age){ super.call(this,name); this.age = age; } inheritPrototype(sub,super); sub.prototype.sayAge = function(){ alert(this.age); }; var instance = new sub("Barney",32); instance.sayName();//Barney instance.sayAge();//32
instance instanceof super; //false 不知道为什么会是false
instance instanceof sub; //true