• class基础语法


    ES5声明一个类

    let Animal = function (type) {

      this.type = type

    }

    Animal.prototype.eat = function () {

      console.log('eat')

    }

    ES6声明一个类

    class Animal {

      // 构造函数

      constructor () {

        this.type = type

      }

      eat () {

        console.log('eat')

      }

    }

    用class声明类只是ES5声明类的一个语法糖

    getter setter可以控制属性的读写

    let _age = 1 // 相当于私有属性,外部访问不到
    class Animals {
      constructor (kind) {
        this.kind = kind
      }
      get age () {
        return _age
      }
      set age(val) {
        _age = val
      }
      shout () {
        console.log('...')
      }
    }
    
    let dog = new Animals('dog')
    console.log(dog.age)
    dog.age = 2
    console.log(dog.age)

     类的静态方法

    class Animal {
      constructor (kind) {
        this.kind = kind
      }
      static shout () {
        console.log('这里是类的静态方法')
      }
    }
    Animal.shout()
    
    // 在ES5里就是 Animal.shout = function () {}

    类的继承

    // ES5
    let Animal = function (kind) {
      this.kind = kind
    }
    
    Animal.prototype.shout = function () {
      console.log('...')
    }
    
    let Dog = function () {
      // 初始化父类的构造函数
      Animal.call(this, 'dog')
    }
    
    Dog.prototype = Animal.prototype
    // ES6
    class Animal {
      constructor (kind) {
        this.kind = kind
      }
      static shout () {
        console.log('这里是类的静态方法')
      }
    }
    
    class Dog extends Animal {
      constructor (kind, color) {
        super(kind)
        this.color = color
      }
    }
    let dog = new Dog('dog', 'white')
    console.log(dog.kind)
    console.log(dog.color)
    
    dog
    white
  • 相关阅读:
    iOS开发--UILabel可以显示
    网络编程之IO模型——IO模型比较分析
    网络编程之IO模型——异步IO
    网络编程之IO模型——多路复用IO
    网络编程之IO模型——非阻塞IO
    网络编程之IO模型——阻塞IO
    Linux基本命令
    Linux界面介绍
    Linux系统目录介绍
    Linux的前世今生
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/12637283.html
Copyright © 2020-2023  润新知