六种继承方式

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>原型继承</title>
 6 </head>
 7 <body>
 8     
 9 </body>
10 </html>
11 <script src="jquery-1.11.3.js"></script>
12 <script>
13     function Person(name,age){
14         this._name = name;
15         this.age = age;
16         
17     }
18     Person.prototype.eat = function(){
19         console.log("吃--------------")
20     }
21     Person.prototype.sleep = function(){
22         console.log("睡--------------")
23     }
24     function Man(name,age,sex){
25         /*call(this,值1,值2,值3)和apply(this,[])都可以用来属性继承、方法借用等操作,参数1都是this的指向*/
26         // Person.call(this,name,age);
27         Person.apply(this,[name,age]);
28         this.sex = sex;
29     }
30 /*原型继承*/
31     // Man.prototype = Person.prototype;//原型继承,添加新方法,父级也会有,称为污染父级
32 
33 /*原型拷贝*/
34 /*    for(var key in Person.prototype){
35         Man.prototype[key] = Person.prototype[key];
36     }*/
37 
38 /*原型链继承*/
39     
40     // Man.prototype = new Person();//原型对象指向发生改变,少了constructor,多了不必要的属性
41 
42 /*混合式继承*/    
43     Man.prototype = {
44         constructor:Man,
45         __proto__:Person.prototype
46     }
47 
48 
49 /*寄生继承*/
50     /*function fn(){}
51     fn.prototype = Person.prototype;
52     Man.prototype = new fn();
53     Man.prototype.constructor = Man;*/    
54 
55     Man.prototype.run = function(){
56 
57     }
58     console.log(new Person());
59     console.log(new Man());
60     console.log(Person.prototype);
61     console.log(Man.prototype);
62     
63 /*ES6中的extends super继承*/
64 
65     class A{
66         constructor(name,age,sex){
67             this._name = name;
68             this.age = age;
69             this.sex = sex;
70         }
71         sing(){
72             console.log("chang");
73         }
74         work(){
75             console.log("工作");
76         }
77     }
78     class B extends A{
79         constructor(m,name,age,sex){
80             super(name,age,sex);
81             this.m = m;
82         }
83         play(){
84             console.log("玩")
85         }
86     }
87     console.log([A]);
88     console.log([B]);
89 </script>

猜你喜欢

转载自www.cnblogs.com/dinner/p/9060616.html