zoukankan      html  css  js  c++  java
  • es6 类

    类的定义

    class Animal {
        //构造函数,创建这个类时会执行的函数
        constructor(color){
            //this当前对象
            console.log("构造")
            this.color=color
        }
    }
    const myCat = new Animal("");
    console.log(myCat)
    • constructor: 构造函数
    • this : 当前实例
    • super: 它的父类

    类的继承   class Cat extends Animal

    <script>
            class Animal {
                constructor(color) {
                    this.color = color
                }
                eat() {
                    console.log('爱吃鱼');
                }
    
            }
            class Cat extends Animal {
                constructor(color, name) {
                    super(color)
                    this.name = name
                }
            }
            let myCat = new Cat('黑白', '皮皮')
            myCat.eat()
            console.log(myCat.color)
            console.log(myCat.name)
        </script>

     

    通过static关键字可以声明静态的方法,静态方法归属于类而不是实例 也可声明静态变量

    普通的方法归属于实例,需要通过实例调用

    <script>
            class Animal {
                //IE不识别静态属性
                static props = {
                    name:"啦啦啦"
                } 
                constructor(color,name){
                    this.color = color;
                    this.name = name;
                }
                //通过static关键词可以声明静态方法,静态方法属于类而不是实例
                static getName (){
                    console.log('静态方法')
                    return this
                }
                eat (){
                    console.log(this.name+'爱吃鱼')
                }
            }
            let bigCat = new Animal('黑白','皮皮') 
            let smallCat = new Animal('白花', '球球') 
            bigCat.eat();
            smallCat.eat();
            console.log(Animal.getName())
            console.log(Animal.props.name)
        </script>
     
  • 相关阅读:
    204. 计数质数
    236. 二叉树的最近公共祖先
    优先队列和哈夫曼树
    185. 部门工资前三高的所有员工(求组内前几的值)
    部门工资最高的员工(求组内最大值)
    回调函数的案例
    单链表
    动态数组
    一致性哈希算法的基本原理
    只用2GB内存在20亿个整数中找到出现次数最多的数
  • 原文地址:https://www.cnblogs.com/guirong/p/13611169.html
Copyright © 2011-2022 走看看