• 继承


    javascript继承的实现,主要有几个点需要注意:

    • 子类中call父类,达到继承父类中的所有属性和方法
    • 创建一个立即执行的闭包,闭包中包含:
      • 创建一个空对象
      • 将父类的prototype赋值给空对象的prototype
      • 子类的prototype等于new一个空对象,实现了子类继承父类的prototype

    实现代码如下:

     1 (function () {
     2 
     3     function SuperType() {
     4         this.superName = 'Super Cheery'
     5 
     6         this.superSayHi = function () {
     7             console.log('hi')
     8         }
     9     }
    10 
    11     SuperType.prototype.superPrototypeSayHi = function () {
    12         console.log('hi')
    13     }
    14 
    15     function SubType() {
    16         // 重点1
    17         SuperType.call(this)
    18         this.subName = 'Sub Cheery'
    19 
    20         this.subSayHi = function () {
    21             console.log('hi')
    22         }
    23     }
    24 
    25     SubType.prototype.subPrototypeSayHi = function () {
    26         console.log('hi')
    27     }
    28 
    29     // 节省内存和变量污染
    30     !function () {
    31         // 重点2
    32         var Super = function () { }
    33         Super.prototype = SuperType.prototype
    34         SubType.prototype = new Super
    35 
    36         console.log(new SubType)
    37     }()
    38 
    39 })();
  • 相关阅读:
    实例协议分析RFC1483:AAL5和几种常见ADSL接入技术
    2.2.3 Runaround Numbers
    2.2.2 Subset Sums
    2.2.1 Preface Numbering
    Dynamic Programming
    Data Structures
    2.1.5 Hamming Codes
    2.1.4 Healthy Holsteins
    2.1.3 Sorting a Three-Valued Sequence
    2.1.2 Ordered Fractions
  • 原文地址:https://www.cnblogs.com/ch11ry/p/7501174.html
Copyright © 2020-2023  润新知