上代码
function SuperType(name){ this.name = name; this.colors = ["red","blue","green"]; } SuperType.prototype.sayName = function(){ console.log(this.name); } function SubType(name , age){ SuperType.call(this,name); this.age = age; } SubType.prototype = new SuperType(); //留意下面这一句的作用 SubType.prototype.constructor = SubType; SubType.prototype.sayAge = function(){ console.log(this.age); } var instance1 = new SubType("HEDONGHUI",22); instance1.colors.push("black"); console.log(instance1.colors); instance1.sayName(); instance1.sayAge(); var instance2 = new SubType("heod",23); console.log(instance2.colors); instance2.sayName(); instance2.sayAge();
SubType.prototype.constructor = SubType;
这句话就是为了修正因为继承SuperType对象所有成员后,SubType的构造器也指向了SuperType的问题.
之继承父类的prototype上的方法,父类构造器中的属性不继承,并且只继承自己的属性