1. 程式人生 > >【JavaScript高階】10、物件高階(繼承模式)

【JavaScript高階】10、物件高階(繼承模式)

一、原型鏈繼承

方式1: 原型鏈繼承
  1. 套路
    1. 定義父型別建構函式
    2. 給父型別的原型新增方法
    3. 定義子型別的建構函式
    4. 建立父型別的物件賦值給子型別的原型
    5. 將子型別原型的構造屬性設定為子型別
    6. 給子型別原型新增方法
    7. 建立子型別的物件: 可以呼叫父型別的方法
  2. 關鍵
    1. 子型別的原型為父型別的一個例項物件
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>01_原型鏈繼承</title>
</head>
<body>
<script type="text/javascript">
  function Supper() {  //定義父型別建構函式
    this.supProp = 'Supper prototype'
  }
  Supper.prototype.showSupperProp = function () {  //給父型別的原型新增方法
    console.log(this.supProp)
  }
  //子型別
  function Sub() {  //定義子型別的建構函式
    this.subProp = 'sub prototype'
  }
  Sub.prototype = new Supper()  // 建立父型別的例項物件賦值給子型別的原型****
  Sub.prototype.constructor = Sub//將子型別的原型的構造屬性設定為子型別****
  Sub.prototype.showSubProp = function () {  //給子型別原型新增方法
    console.log(this.subProp)
  }
  var sub = new Sub()
  sub.showSubProp()
  sub.showSupperProp()  //可以呼叫父型別的方法
  console.log(sub)
</script>
</body>
</html>

 

二、借用建構函式繼承(非真正) 

方式2: 借用建構函式繼承(假的)
1. 套路:
  1. 定義父型別建構函式
  2. 定義子型別建構函式
  3. 在子型別建構函式中呼叫父型別構造
2. 關鍵:
  1. 在子型別建構函式中通過call()呼叫父型別建構函式
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>02_借用建構函式繼承</title>
</head>
<body>
<script type="text/javascript">
  function Person(name, age) {
    this.name = name
    this.age = age
  }
  function Student(name, age, price) {
    Person.call(this, name, age)  // 相當於: this.Person(name, age)
    /*this.name = name
    this.age = age*/
    this.price = price
  }

  var s = new Student('Tom', 20, 14000)
  console.log(s.name, s.age, s.price)

</script>
</body>
</html>

 三、組合繼承

方式3: 原型鏈+借用建構函式的組合繼承
1. 利用原型鏈實現對父型別物件的方法繼承
2. 利用call()借用父型別構建函式初始化相同屬性
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>03_組合繼承</title>
</head>
<body>
<script type="text/javascript">
  function Person(name,age) {
    this.name = name
    this.age = age
  }
  Person.prototype.setName = function (name) {
    this.name = name
  }
  function Student(name,age,price) {
    Person.call(this,name,age)  // 為了得到屬性
    this.price = price
  }
  Student.prototype = new Person()  // 為了能看到父型別的方法
  Student.prototype.constructor = Student  // 修正constructor屬性
  Student.prototype.setPrice = function (price) {
    this.price = price
  }
  var s = new Student('tom',12,12000)
  console.log(s.name,s.age,s.price)
  s.setName('bob')
  s.setPrice(16000)
  console.log(s.name,s.age,s.price)

</script>
</body>
</html>