您好,欢迎访问一九零五行业门户网

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

本篇文章给大家带来的内容是关于对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 functiondemo.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中类的简单理解(附示例)的详细内容。
其它类似信息

推荐信息