• ES6 class 技术点拾遗


    语法

    • 方法不需要加function,方法之间不需要加分号
    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    
        toString() {
            return '(' + this.x + ', ' + this.y + ')';
        }
        getX() {
            return this.x;
        }
    }

    类的prototype

    类的方法都定义在prototype上,但是是不可以枚举的。

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    
        toString() {
            return '(' + this.x + ', ' + this.y + ')';
        }
        getX() {
            return this.x;
        }
    }
    Point.prototype.aa = function (){}
    console.log(Object.keys(Point.prototype))
    //输出['aa']

    静态方法

    • 静态方法的this指向类,而不是示例
    • 静态方法可以和实力方法重名
    • 父类的静态方法可可以被子类继承
    • class内部只有静态方法,而没有静态属性
    class Foo {
      static bar () {
        this.baz();
      }
      static baz () {
        console.log('hello');
      }
      baz () {
        console.log('world');
      }
    }
    
    Foo.bar() // hello
    // 以下两种写法都无效
    class Foo {
      // 写法一
      prop: 2
    
      // 写法二
      static prop: 2
    }
    
    Foo.prop // undefined

    继承

    • 使用extends关键字实现继承
    • 使用super调用父类的构造函数
    • super函数必须在子类的构造函数中调用,否则会报错。
    • super函数位于子类构造函数的第一行!因为子类的this必须先通过父类的构造函数完成构造。不调用super方法,子类就得不到this对象。也就是说子类若是有构造函数的话,构造函数的第一行必须是super。
    • super当做函数使用时,即super(),只能用在子类的构造函数中。当做对象使用时,即super.方法(),指向父类的原型对象(在静态方法中指向父类),此时注意是调用父类原型上的方法(或者父类的静态方法),而不是实例方法;同时this指向子类的实例。
    class ColorPoint extends Point {
      constructor(x, y, color) {
        super(x, y); // 调用父类的constructor(x, y)
        this.color = color;
      }
    
      toString() {
        return this.color + ' ' + super.toString(); // 调用父类的toString()
      }
    }
  • 相关阅读:
    dedecms织梦修改标题默认长度
    Python正课68 —— 实现面向对象编程
    Python正课67 —— 面向对象介绍
    Win10系统下提示VMware与Device/Credential Guard不兼容的解决方法
    周考5 月考1 内容
    Python正课66 —— ATM + 购物车 小有成就
    Python正课65 —— ATM + 购物车 架构
    Python正课64 —— re模块
    Python正课63 —— logging模块
    Python正课62 —— subprocess模块
  • 原文地址:https://www.cnblogs.com/mengfangui/p/10060249.html
Copyright © 2020-2023  润新知