参考
class 基本语法
- //class 实现
- class Point {
- constructor(x, y) {
- this.x = x;
- this.y = y;
- }
- toString() {
- return (this.x, this.y)
- }
- }
- //z 构造函数实现
- function Points(x, y) {
- this.x = x;
- this.y = y;
- }
- Points.prototype.toString = function() {
- return this.x + this.b
- }
- constructor
默认方法, 未显示定义时会默认添加
默认返回实例对象 this
必须使用 new 调用
static 静态方法
类相当于实例的原型, 所有在类中定义的方法, 都会被实例继承如果在一个方法前, 加上 static 关键字, 就表示该方法不会被实例继承, 而是直接通过类来调用, 这就称为静态方法类相当于实例的原型, 所有在类中定义的方法, 都会被实例继承如果在一个方法前, 加上 static 关键字, 就表示该方法不会被实例继承, 而是直接通过类来调用, 这就称为静态方法
静态方法可以被子类继承
- class Foo {
- static classMethod() {
- return 'hello';
- }
- }
- Foo.classMethod() // 'hello'
- var foo = new Foo();
- foo.classMethod()
- // TypeError: foo.classMethod is not a function
继承 extends
在子类的构造函数中, 只有调用 super 之后, 才可以使用 this 关键字, 否则会报错这是因为子类实例的构建, 是基于对父类实例加工, 只有 super 方法才能返回父类实例
- class Point {
- }
- class ColorPoint extends Point {
- }
- class ColorPoint extends Point {
- constructor(x, y, color) {
- super(x, y); // 调用父类的 constructor(x, y)
- this.color = color;
- }
- toString() {
- return this.color + ' ' + super.toString(); // 调用父类的 toString()
- }
- }
- super
函数 super()
作为函数使用, 代表父类的构造函数;
子类的构造函数必须执行一次 super();
- class A {
- constructor() {
- console.log(new.target.name);
- }
- }
- class B extends A {
- constructor() {
- super();
- }
- }
- new A() // A
- new B() // B
super 虽然代表了父类 A 的构造函数, 但是返回的是子类 B 的实例, 即 super 内部的 this 指的是 B
对象 super
在普通方法中 指向父类的原型对象
在静态方法中 指向 父类
来源: http://www.jianshu.com/p/a7503197751e