JS前端开发联盟群JavaScript

[JavaScript] class

2016-03-05  本文已影响34人  何幻

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对象上调用。

上一篇下一篇

猜你喜欢

热点阅读