[JavaScript] class

ES6中的class基于原型继承创建类。

(1)class只是原型继承的语法糖

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    
    toString() {
        return '('+this.x+', '+this.y+')';
    }
}

相当于:

function Point(x,y){
    this.x=x;
    this.y=y;
}

Point.prototype={
    toString:function(){
        return '('+this.x+', '+this.y+')';
    }
};

注:
<u></u>class定义中的实例方法,不需要function关键字,
如果定义的是一个generator方法,则在前面加*,例如“* generatorFunc(...){...}

(2)class声明的类并不会提升。

var p = new Polygon();     // ReferenceError

class Polygon {}

(3)class也可以使用表达式的方式定义

const MyClass = class Me {
    getClassName() {
        return Me.name;    //Me
    }
};

let inst = new MyClass();
inst.getClassName();    // Me
Me.name    // ReferenceError: Me is not defined

类的名字是MyClass而不是MeMe只在class内部可用,指代当前类。
如果class内部没有用到Me,可以class表达式可以省略Me

(4)继承

class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y);
        this.color = color;
    }

    toString() {
        return this.color + ' ' + super.toString();
    }
}

子类必须在constructor方法中调用super方法,否则新建实例时会报错
在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错

(5)原型关系

class A{}
class B extends A {}

为了让B继承A的类方法,

B.__proto__ === A

B.classMethod ===B.__proto__.classMethod===A.classMethod

为了让B的实例继承A的实例方法,

B.prototype.__proto__ === A.prototype

(new A).instanceMethod
===(new A).__proto__.instanceMethod
===A.prototype.instanceMethod

(new B).instanceMethod
===(new B).__proto__.instanceMethod
===B.prototype.instanceMethod
===B.prototype.__proto__.instanceMethod
===A.prototype.instanceMethod

 (new B).instanceMethod===(new A).instanceMethod

注:
类方法,可以在class定义的方法前加static实现。

class A{
    static classMethod(){}
}

类方法,也可以在super对象上调用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,129评论 3 11
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • Class 学过Java的小伙伴会发现, 这个class和Java里的class基本语法并没有什么区别... 下面...
    刘翾阅读 997评论 2 2
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,788评论 0 9
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,769评论 18 399