关于 JS 继承,构造函数的指向问题

这里主要记录一个构造函数,因为继承,然后引起 construct 属性指向紊乱问题

详细解说看阮一峰大佬的博客:Javascript面向对象编程(二):构造函数的继承

<!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 A () {
      this.name = 'Abner'
      this.color = [1,2] // 这里只有引用类型的值会发生这个事情
    }
    A.prototype.sayName = function () {
      console.log(this.name)
    }
    A.prototype.logColor = function () {
      console.log(this.color)
    }
    function B () {
      this.age = 22
    }
    B.prototype = new A()
    B.prototype.construct = B // 纠正构造函数的指向,否则回引起构造函数紊乱问题
    B.prototype.sayAge = function () {
      this.color.push(8)
      console.log(this.age)
      console.log(this.name)
    }
    const a1 = new B()
    console.log(B)
    console.log(a1)
  </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值