javascriptは継承の3つの方式を実現します.原型の継承、構造関数の継承、組合せの継承、アナログextens方法の継承…
21445 ワード
javascriptで継承を実現する3つの方法:原型継承、構造関数の引継ぎ、混合継承:
1 /*
2 js
3
4 js :
5 1 .prototype =
6 2 .constructor = ( )
7 3 .isPrototypeOf( )
8 4
9 */
10
11
12 /*
13 1
14
15 :
16 1 Son.prototype new Father()
17 2 ,
18 3 Son.prototype.constructor Father
19 4 Son.prototype.prototype Father.prototype
20 :
21
22 : , 。
23 */
24
25 //
26 function Father(name){
27 this.name = name;
28 }
29 //
30 Father.prototype={
31 constructor: Father,
32 id:10,
33 sayName:function(){
34 alert(this.name);
35 }
36 };
37
38 //
39 function Son(age){
40 this.age = age;
41 }
42 //
43 Son.prototype = new Father(" ");
44
45 //
46 var s1 = new Son(18);
47 //s1.sayName(); //
48 //alert(s1.age); //18
49
50 /*
51 :
52
53 : , 。
54 */
55
56
57
58
59 /*
60 2 ( ) ,
61 call apply ,
62 */
63 //
64 function Father(name){
65 this.name = name;
66 }
67 //
68 Father.prototype.id = 10;
69
70 //
71 function Son(name,age){
72 //name
73 Father.call(this,name);
74 this.age = age;
75 }
76 //
77 var s2 = new Son("z3",18);
78 //alert(s2.name); //z3
79 //alert(s2.age); //18
80
81 /*
82 ( ) :
83 :
84 :
85 */
86
87
88 /*
89 3 :
90 :
91 :1
92 2
93 : , call
94 ,
95 */
96 //
97 function Father(name){
98 this.name = name;
99 }
100 //
101 Father.prototype = {
102 constructor:Father,
103 id:10,
104 sayName:function(){
105 alert(this.name);
106 }
107 };
108 //
109 function Son(name,age){
110 //
111 Father.call(this,name);
112 this.age = age;
113 }
114 // ,
115 Son.prototype = new Father();
116
117 //
118 var s3 = new Son("l4",20);
119 //alert(s3.name); //
120 //alert(s3.id); //
121 //alert(s3.age); //
122 //s3.sayName(); //
123 /*
124 :
125 :1
126 2
127 : , call
128 ,
129 */
しかし、上の3つの方法は混合継承でも弊害があります.以下はjsでextensの継承者を模擬して、父類を重複しない構造関数を実現します.
1 /*
2 javascript extends ,
3 :
4 1
5 2
6 3
7 */
8
9 //1 extends
10 function extend(son,father){
11 //
12 var f = new Function(); // ,
13 f.prototype = father.prototype; //
14 son.prototype = new f(); // , ,
15 // superClass ,
16 son.superClass = father.prototype;
17 //
18 if(father.prototype.constructor == Object.prototype.constructor){
19 father.prototype.constructor = father;
20 }
21 }
22 //2
23 function Father(name){
24 this.name = name;
25 }
26 //
27 Father.prototype = {
28 constructor: Father,
29 sayName:function(){
30 alert(this.name);
31 }
32 };
33
34
35 //3
36 function Son(name,age){
37 // :
38 // Father.call(this , name); , , , extentds ,
39 Son.superClass.constructor.call(this , name); //Son.superClass ,consturctor
40 this.age = age;
41 }
42 //
43 //Son.prototype = new Father(); // , ,
44 //
45
46
47
48 extend(Son,Father);
49
50
51
52 //
53 var s4 = new Son("haha",33);
54 alert(s4.name); //haha
55 alert(s4.age); //33
56 s4.sayName(); //haha
57 //
58 s4.sayName = function(){
59 alert("hello i am son");
60 };
61 s4.sayName(); //hello i am son sayName
62 //
63 Son.superClass.sayName.call(s4); //haha
64
65
66
転載先:https://www.cnblogs.com/Lin-Yi/p/7446841.html