Javascript:构造函数中原型对象(prototype)

  • Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象,称为原型对象。这个原型对象可以挂载函数,对象实例化不会多次创建原型上的函数,节约内存。
  • 可以把不变的方法,直接定义在prototype对象上,这样所有的实例对象就可以共享这些方法。
  • 公共的属性定义在构造函数上,公共的方法定义到构造函数的原型对象上。
  • 构造函数和原型对象函数中的this都指向实例化的对象。

示例

打印构造函数的prototype属性

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 声明构造函数
    function Star(uname, age) {
      this.uname = uname
      this.age = age
      this.sing = function () {
        console.log('唱歌')
      }
    }
    const star1 = new Star('歌手1', 30)
    const star2 = new Star('歌手2', 28)

    console.dir(Star.prototype)
  </script>
</body>

</html>

在这里插入图片描述

在构造函数的原型对象上定义公共的方法

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 声明构造函数
    // 公共的属性写到构造函数里面
    function Star(uname, age) {
      this.uname = uname
      this.age = age
    }
    // 公共的方法写到原型对象上
    Star.prototype.sing = function () {
      console.log('唱歌')
    }
    const star1 = new Star('歌手1', 30)
    const star2 = new Star('歌手2', 28)
    star1.sing()
    star2.sing()
    console.log(star1.sing === star2.sing)   // 返回true

  </script>
</body>

</html>

在这里插入图片描述

构造函数中的this指向实例对象

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let that
    function Star(uname) {
      that = this
      this.uname = uname
    }
    // 实例对象是star1
    // 构造函数中的this就是实例对象
    const star1 = new Star('歌手1 ')
    console.log(that === star1)
  </script>
</body>

</html>

在这里插入图片描述

原型对象函数中的this指向实例对象

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let that
    function Star(uname) {
      this.uname = uname
    }
    Star.prototype.sing = function () {
      that = this
      console.log('唱歌')
    }
    // 实例对象是star1   
    const star1 = new Star('歌手1 ')
    star1.sing()
    console.log(that === star1)  // 返回true
  </script>
</body>

</html>

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值