javascript中的继承
原型链模式和组合继承模式的区别就在于:继承模式中调用了两次基类的构造函数,结果实例中的属性就屏蔽了原型中的同名属性(这样做可以避免各个实例共享的引用实例相互影响)。组合继承是javascript中最常用的继承模式。
例如
View Code
1 function Person(name){
2 this.name = name;
3 this.colors = ["red","blue","white"];
4 }
5 Person.prototype.sayName = function(){
6 return this.name;
7 }
8 function Student(name,age){
9 Person.call(this,name);//组合模式中需要这句
10 this.age = age;
11 }
12 Student.prototype = new Person();
13 Student.prototype.sayAge = function(){
14 return this.age;
15 }
16 var student = new Student("fsdf",12);
17 student.colors.push("black");
18
19 alert(Student.prototype.colors);//red,blue,white
20 alert(student.name);//fsdf
21 alert(student.colors);//red,blue,white,black
寄生组合模式
View Code
1 function object(o){
2 function F(){}
3 F.prototype = 0;
4 return new F();
5 }
6 function inheritPrototype(student,person){
7 var prototype = object(person.prototype);
8 prototype.constructor = student;
9 student.prototype = prototype;
10 }
11 function Person(name){
12 this.name = name;
13 this.colors = ["red","blue","white"];
14 }
15 Person.prototype.sayName = function(){
16 return this.name;
17 }
18 function Student(name,age){
19 Person.call(this,name);
20 this.age = age;
21 }
22 inheritPrototype(Student,Person);
23 Student.prototype.sayAge = function(){
24 alert(this.age);
25 }
26 var student = new Student("fsdf",12);
27 student.colors.push("black");
28 alert(Student.prototype.colors);//undefined
29 alert(student.name);//fsdf
30 alert(student.colors);//red,blue,white,black
比较两种模式,很容易发现在寄生组合模式中Student.prototype上面没有创建不必要的属性name和colors,从而提高了效率,同时原型链保持不变。开发人员普遍认为寄生组合式继承是引用类型最理想的继承方式。
YUI的YAHOO.lang.extend()方法采用的就是寄生组合继承。
View Code
浙公网安备 33010602011771号