• 技术文章 >Web开发 >JavaScript

    js使用构造函数的缺点

    小妮浅浅小妮浅浅2021-11-08 13:46:31原创13913

    1、不是原型链继承,只是借用构造函数,所以不能继承原型的属性和方法。

    2、虽然构造函数中定义的属性和方法是可以访问的,但是每个实例都被复制了。

    如果例子太多,方法太多,占用内存很大,那么方法就在构造函数中定义,函数的复用就无从谈起。

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    // 父构造函数

    function Father() {

        this.name = 'father'

        this.speakName1 = function () {

            console.log('speakName1')

        }

        this.speakName2 = function () {

            console.log('speakName2')

        }

        this.speakName3 = function () {

            console.log('speakName3')

        }

        this.speakName4 = function () {

            console.log('speakName4')

        }

    }

    // 父原型上 方法

    Father.prototype.alertName = function () {

        console.log(this.name)

    }

    // 父原型上 属性

    Father.prototype.age = 21

    // 子构造函数

    function Children() {

        Father.call(this)

    }

      

    // 创建子实例

    let c1 = new Children()

    // 调用原型方法,实例访问不到

    c1.alertName()

    // TypeError: c1.alertName is not a function

      

    // 访问原型属性,实例中未定义

    console.log(c1.age)

    // undefined

      

    // 可以访问实例属性,但是每个实例都存有自己一份 name 值

    console.log(c1.name)

    // father

      

    // 可以访问实例方法,但是每个实例都存有自己一份 speakName1() 方法,

    // 且方法过多,内存占用量大,这就不叫复用了

    c1.speakName1()// speakName1

      

    c1.speakName2()// speakName2

      

    c1.speakName3()// speakName3

      

    c1.speakName4()// speakName4

      

    // instanceof isPrototypeOf 无法判断实例和类型的关系

    console.log(Father.prototype.isPrototypeOf(c1))// false

    console.log(c1 instanceof Father)// false

    以上就是js使用构造函数的缺点,希望对大家有所帮助。更多js学习指路:js教程

    推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

    专题推荐:js 构造函数
    上一篇:js子类型重写的注意点 下一篇:js原型链的优缺点

    相关文章推荐

    • java中构造函数的用法规则• java中使用构造函数的好处• java构造函数的三种类型• 构造函数在java的重载方法• python构造函数是什么?• js构造函数的使用注意• js盗用构造函数的实现

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网