ECMAScript 6入门类学习笔记上

类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);  // 正确
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值