JS——原型、constructor属性、对象原型、原型继承、原型链

一、知识点

  • 面向过程:性能好;不灵活、复用性
  • 面向对象:灵活、复用好;性能不好

1、原型

    const arr= new Array(1,2,5,3)
    // 定义数组的扩展方法,任何一个数组实例对象都可以使用
    // 求最大值
    Array.prototype.max = function(){
      // 展开运算符
      return Math.max(...this)
    }
    // 返回5
    console.log(arr.max());

    // 求和
    Array.prototype.sum = function(){
      return this.reduce( ( prev,item ) => prev + item , 0)
    }
    // 返回11
    console.log(arr.sum());

2、constructor属性

3、对象原型

4、原型继承

5、原型链

二、综合案例

封装模态框,打开,关闭

<body>
  <button id="delete">删除</button>
  <button id="login">登录</button>
  <script>
    function Modal(title = '',message = '') {
      // 创建模态框盒子
      this.modalBox = document.createElement('div')
      this.modalBox.className = 'modal'
      this.modalBox.innerHTML = `
      <div class="header">${title} <i>x</i></div>
      <div class="body">${message}</div>
      `
    }
    
    // 关闭
    Modal.prototype.close = function(){
      this.modalBox.remove()
    }

    // 打开
    Modal.prototype.open = function(){
      // 判断页面中是否有modal盒子,有则删除,没有则添加
      const box =document.querySelector('.modal')
      box && box.remove()
      // 把刚才创建的modalBox显示到页面body中
      document.body.append(this.modalBox)
      // 等盒子显示出来,绑定点击事件
      this.modalBox.querySelector('i').addEventListener('click', () => {
        this.close()
      })
    }
    
    // 创建实例化对象
    document.querySelector('#delete').addEventListener('click',() => {
      // 先调用Modal构造函数
      const del = new Modal('温馨提示','您没有权限删除操作')
      del.open()
    })
    document.querySelector('#login').addEventListener('click',() => {
      const log = new Modal('友情提示','您没有权限注册账号')
      log.open()
    })
    </script>
</body>
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值