ES6 学习 -- Class

Class的基本语法
(1)// 定义类
class Point {
  test() {
    console.log("hello test");
  }
}
通过 new 定义好的类即可生成一个类的实例对象
let point = new Point();
point.test(); // 打印 “hello test”

(2)类下面的所有方法,其实是定义在类的prototype(原型)属性上面,如下
class Point {
  test(){...}
  hehe(){...}
  heihei(){...}
}
// 等同于
Point.prototype = {
  test(){...}
  hehe(){...}
  heihei(){...}
}


(3)实例对象的constructor方法指向类的原型对象的constructor,即pointer.constructor === Pointer.prototype.constructor

(4)由于类的方法都是定义在prototype上的,所有类的新方法的添加可以通过Object.assigin()方法一次添加多个方法
Object.assign(Pointer.prototype, {
  huhu(){},
  wawa(){}
})

(5)类实例生成,也必须像ES5那样,通过new 关键字来生成,否则报错,与ES5一样,实例的属性除非显示的定义在其本身(即定义在this对象上),否则是定义在原型上(即定义在class上)

(6)this的指向
类的方法内如果含有this,它默认指向类的实例对象,而在class中定义的方法test,test内部的this指向Class本身,如果直接使用这个方法,报错not found test,如下:
class Logger {
  printName(){
    this.print("jack");
  }
  print(name) {
    console.log(name);
  }
}

const logger = new Logger();
const {printName} = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
/* 此时的this指向printName方法运行的所在环境(运行环境已经不在Logger的作用域内了,故找不到print方法), */

解决方法:在类的构造函数中绑定this
class Logger {
  constructor(){
    this.printName = this.printName.bind(this); // 此时无论在哪里调用printName,this都指向Class
  }
  printName(){

    this.print("jack");

  }

  print(){...}
}

(7)Class的静态方法
类相当于实例的原型,所有定义在类中的方法,都会被实例继承,如果在一个方法前面添加static关键字,那么这个方法不会被实例所继承,只能通过类类调用,如下
class Foo {
  static say() {
    return "rose";
  }
}

let foo = new Foo();
foo.say(); // TypeError: foo.say is not a function
Foo.say(); // "rose",

***类下面的方法前面如果有关键字static的,不会被实例对象继承,只能通过类本身来调用

(8)new.target
Class内部使用new.target返回当前Class,如果当前类有子类,new.target返回子类

猜你喜欢

转载自www.cnblogs.com/secretAngel/p/9699637.html