实例1:
function SuperType(name){ this.name = name; this.colors = ['red','green','blue']; } SuperType.prototype.sayName = function(){ console.log(this.name); } function SubType(name,age){ SuperType.call(this,name); this.age = age; } function inheritPrototype(SubType,SuperType){ SuperType.prototype.constructor = SubType;//把上边的两个函数合并 SubType.prototype = SuperType.prototype; } /** 公用的构造函数 function SubType(name,age){ this.name = name; this.colors = ['red','green','blue']; this.age = age; } */ inheritPrototype(SubType,SuperType); SubType.prototype.sayAge = function(){ console.log(this.age); } var p1 = new SubType('zhangsan',89); p1.sayName(); p1.sayAge(); console.log(p1.colors); console.log(p1);
这个是利用call()和SuperType.prototype.constructor = SubType;//把上边的两个函数合并函数公用一个构造函数