《JavaScript高级程序设计第六章--面向对象》section_04
这一部分,主要解决原型中包含引用类型值带来问题的过程。
借用构造函数的技术(也叫经典继承或伪造对象);
基本思想:在子类构造函数的内部调用超类型构造函数。因此通过使用apply()和call()方法
function SuperType(){ this.colors = ["red","blue","green"]; } function SubType(){ //继承了 SuperType SuperType.call(this); } var instance1 =new SubType(); instance1.colors.push ("black"); alert(instance1.colors); //"red,blue,green,black" var instance2 = new SubType(); alert(instance2.colors); //"red,blue,green"
1.可以传递参数
function SuperType(name){ this.name = name; } function SubType(){ // 继承了SuperType,同时还传递参数 SuperType.call(this,"Nicholas"); //实例属性 this.age = 29; } var instance = new SubType(); alert(instance.name); //"Nicholas"; alert(instance.age); //"29"
2. 借用构造函数的问题
无法避免构造函数模式——使得方法都在构造函数中定义,函数复用无从谈起!而且,在超类型的原型中定义的方法,对子类型而言也是不可见的。
最终采用组合继承(伪经典继承):使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。
1 function SuperType(name){ 2 this.name = name; 3 this.colors = ["red", "blue", "green"]; 4 } 5 6 SuperType.prototype.sayName = function(){ 7 alert(this.name); 8 }; 9 10 function SubType(name, age){ 11 SuperType.call(this, name); 12 13 this.age = age; 14 } 15 16 SubType.prototype = new SuperType(); 17 18 SubType.prototype.sayAge = function(){ 19 alert(this.age); 20 }; 21 22 var instance1 = new SubType("Nicholas", 29); 23 instance1.colors.push("black"); 24 alert(instance1.colors); //"red,blue,green,black" 25 instance1.sayName(); //"Nicholas"; 26 instance1.sayAge(); //29 27 28 29 var instance2 = new SubType("Greg", 27); 30 alert(instance2.colors); //"red,blue,green" 31 instance2.sayName(); //"Greg"; 32 instance2.sayAge(); //27

浙公网安备 33010602011771号