面向对象的程序设计(四)原型链继承
function SuperType() { this.property = true; } SuperType.prototype.getSuperValue = function () { return this.property; } function SubType() { this.subproperty = false; } //继承了SuperType SubType.prototype = new SuperType(); SubType.prototype.getSubValue = function () { return this. subproperty; } var instance = new SubType(); alert(instance.getSuperValue());//true alert(instance instanceof Object);//true alert(instance instanceof SubType);//true alert(instance instanceof SuperType);//true alert(Object.prototype.isPrototypeOf(instance));//true alert(SubType.prototype.isPrototypeOf(instance));//true alert(SuperType.prototype.isPrototypeOf(instance));//true //SubType继承了SuperType,通过创建SuperType的实例。 //弊端1:看下面的列子,instance3的colors属性居然被instance2改变了 //弊端2:没有办法在不影响所有对象实例的情况下,给超类型构造函数(SuperType2)传递参数 function SuperType2() { this.colors = ["red", "blue"]; } function SubType2() { } SubType2.prototype = new SuperType2(); var instance2 = new SubType2(); instance2.colors.push("black"); alert(instance2.colors);//"red", "blue", "black" var instance3 = new SubType2(); alert(instance3.colors);//"red", "blue", "black"