class类

  1. js语言传统方法是通过构造函数,定义并生成新对象
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    function Fn(x, y) {
      this.x = x
      this.y = y
    }
    Fn.prototype.toTo = function () {
      console.log(this.x + this.y)
    }
    fn = new Fn(1, 2)
    console.log(fn)
    fn.toTo()
  </script>
</body>
</html>
  1. 使用es6中的class类定义生成新对象
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    class Fn {
      constructor(x, y) {
        this.x = x
        this.y = y
      }
      toTo() {
        console.log(this.x + this.y)
      }
    }
    console.log(Fn)
    var fn = new Fn(1, 2)
    console.log(fn)
    fn.toTo()
  </script>
</body>
</html>

3.es5实现继承(构造函数和原型链组合继承)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    function Parent(name) {
      this.name = name
    }
    Parent.prototype.getName = function() {
      console.log(this.name)
    }

    function Child(name) {
      Parent.call(this, name)
    }
    Child.prototype = new Parent()
    Child.prototype.constructor = Child
    var child = new Child('haha')
    child.getName()
    console.log(child.name)
  </script>
</body>
</html>

4.es6实现继承

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>

    class Parent {
      constructor(x, y) {
        this.x = x
        this.y = y
      }
      say() {
        console.log(this.x + this.y)
      }
    }
    class Child extends Parent {
      constructor(x, y, z) {
        super(x, y) // super的含义,父类的调用,但是返回的是子类的实例
        this.z = z
      }
      call() {
        console.log(this.x + this.y + this.z)
      }
    }
    const child = new Child(2, 3, 4)
    console.log(child, 'child')
    child.call()
    child.say()
  </script>
</body>
</html>

5.super关键字
第一种情况,super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值