对象继承模式

方式一;原型链继承

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>01_原型链继承</title>
 6 </head>
 7 <body>
 8 <!--
 9 方式1: 原型链继承
10   1. 套路
11     1. 定义父类型构造函数
12     2. 给父类型的原型添加方法
13     3. 定义子类型的构造函数
14     4. 创建父类型的对象赋值给子类型的原型
15     5. 将子类型原型的构造属性设置为子类型
16     6. 给子类型原型添加方法
17     7. 创建子类型的对象: 可以调用父类型的方法
18   2. 关键
19     1. 子类型的原型为父类型的一个实例对象
20 -->
21 <script type="text/javascript">
22   //父类型
23   function Supper() {
24     this.supProp = 'Supper property'
25   }
26   Supper.prototype.showSupperProp = function () {
27     console.log(this.supProp)
28   }
29 
30   //子类型
31   function Sub() {
32     this.subProp = 'Sub property'
33   }
34 
35   // 子类型的原型为父类型的一个实例对象
36   Sub.prototype = new Supper()
37   // 让子类型的原型的constructor指向子类型
38   Sub.prototype.constructor = Sub
39   Sub.prototype.showSubProp = function () {
40     console.log(this.subProp)
41   }
42 
43   var sub = new Sub()
44   sub.showSupperProp()  // Sub.prototype = new Supper()  这句非常重要,可以调用到父类型中原型的方法
45   // sub.toString()
46   sub.showSubProp()
47 
48   console.log(sub)  // Sub
49 
50 
51 
52 </script>
53 </body>
54 </html>

效果图

方式二;

借用构造函数继承(假的)
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>02_借用构造函数继承</title>
 6 </head>
 7 <body>
 8 <!--
 9 方式2: 借用构造函数继承(假的),如果父类原型还有方法,子类是访问不到的
10 1. 套路:
11   1. 定义父类型构造函数
12   2. 定义子类型构造函数
13   3. 在子类型构造函数中调用父类型构造
14 2. 关键:
15   1. 在子类型构造函数中通用call()调用父类型构造函数,子类只能部分继承(获取父类的属性),如果父类原型还有属性方法,子类无法访问
16 -->
17 <script type="text/javascript">
18   function Person(name, age) {
19     this.name = name
20     this.age = age
21   }
22   function Student(name, age, price) {
23     Person.call(this, name, age)  // 相当于: this.Person(name, age)
24     /*this.name = name
25     this.age = age*/
26     this.price = price
27   }
28 
29   var s = new Student('Tom', 20, 14000)
30   console.log(s.name, s.age, s.price)
31 
32 </script>
33 </body>
34 </html>
原型链+借用构造函数的组合继承
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>03_组合继承</title>
 6 </head>
 7 <body>
 8 <!--
 9 方式3: 原型链+借用构造函数的组合继承
10 1. 利用原型链实现对父类型对象的方法继承
11 
12 -->
13 <script type="text/javascript">
14   function Person(name, age) {
15     this.name = name
16     this.age = age
17   }
18   Person.prototype.setName = function (name) {
19     this.name = name
20   }
21 
22   function Student(name, age, price) {
23     Person.call(this, name, age)  // 为了得到父类型的属性
24     this.price = price
25   }
26   Student.prototype = new Person() // 为了能看到父类型的方法
27   Student.prototype.constructor = Student //修正constructor属性
28   Student.prototype.setPrice = function (price) {
29     this.price = price
30   }
31 
32   var s = new Student('Tom', 24, 15000)
33   s.setName('Bob')
34   s.setPrice(16000)
35   console.log(s.name, s.age, s.price)  // Bob 24 16000
36 
37 </script>
38 </body>
39 </html>
原文地址:https://www.cnblogs.com/fsg6/p/12792788.html