对es6中类的简单理解(附示例)

不言
不言转载
2018-10-25 15:43:331446浏览

本篇文章给大家带来的内容是关于对es6中类的简单理解(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

类class

基本概念,记录以便自己后面加深理解

了解类是什么

class是什么?不妨写一个看看

class Demo {
    constructor() {
        this.a = 1;
        this.b = this.f;
    }
    f() {
        return this;
    }
}
Demo.prototype; //{
                //  constructor: class Demo
                //  f: ƒ f()           
                //  __proto__: Object }

Demo的原型可以看到这三个属性都是不可遍历的并且与Demo类相比就多了一个__proto__原型链。我们再new一个Demo看一下

let o = new Demo();
console.log(Object.getPrototypeOf(o));  //{
                                        //  constructor: class Demo
                                        //  f: ƒ f()           
                                        //  __proto__: Object }

实际上Demo类相当于Demo实例的原型

class中的constructor

在我看来

    constructor() {
        this.a = 1;
        this.b = this.f;
    }

这部分相当于es5中构造函数的作用,在new的过程中对this进行赋值,并返回this也就成了实例对象
因此你在constructor中return了一个对象且不等于null那么实例对象就是return的值,和es5构造函数一样的效果

class中的方法

    f() {
        return this;
    }

这个方法最终属于在实例对象的原型链上不可遍历方法,因此也能被实例对象使用

新知识点

class的静态方法

表示该方法不会被实例继承,而是直接通过类来调用

class Demo {
    constructor() {
        this.a = this;
        this.b = this.f;
    }
    static g() {
        return this;
    }
    static f() {
        return this;
    }
}
let o = new Demo(); 
//console.log(o.b());    //not a function
//console.log(o.g());     //not a function
Demo.g() === Demo;        //true

静态方法中的this指向类自己,而this.a = this则指向实例对象自己

静态方法可以被子类继承

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
}

Bar.classMethod() // 'hello'

静态方法可以从super对象上调用

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too';
  }
}

Bar.classMethod() // "hello, too"

Class 内部只有静态方法,没有静态属性

class表达式的立即执行写法

var o =  new class {
    constructor(n) {
        this.a = n;
        this.b = this.f;
    }
    g() {
        return n;
    }
    f() {
        return this;
    }

}(1)

o.a;             // 1

class类声明不存在变量提升

new.target 属性

是在new后返回一个对象,例如es5中构造函数f不是通过new调用返回undefined,通过new调用返回构造函数自己

function f() {
    return new.target;
}
console.log((new f()) === f);       //true

而class类中,则返回class自身。和静态方法中this是一样的;new得是哪个类就返回哪个类

class Shape {
  constructor() {
    if (new.target === Shape) {
      throw new Error('本类不能实例化');
    }
  }
}

class Rectangle extends Shape {
  constructor(length, width) {
    super();
    // ...
  }
}

var x = new Shape();  // 报错
var y = new Rectangle(3, 4);  // 正确

以上就是对es6中类的简单理解(附示例)的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除