es6中的class声明

es6中提出了class来声明一个构造函数,那么关于class声明的构造函数就必须遵循class的一些规则,接下来让我们看一下class的几条规则以及与es5中声明构造函数的不同点:

1.class声明存在变量提升,但不会初始化赋值

es5:

const state = new State(); // 是被允许的   function声明的函数 会提升到作用域顶部

function State() {

  this.state = 42;

}

es6:

const foo = new Foo(); // ReferenceError: Foo is not defined    此时class声明的foo 进入了暂时性死区 就相当于let const声明的变量是一样的的
class Foo {
  constructor() {
    this.foo = 42;
  }
}

2.class声明的构造函数内部 会使用严格模式

es5:

function State() {

  state 55;   //在es5中 虽然state是一个未被声明的变量 但是此时是不会报错的  采用的是非严格模式

}

const state new State();

es6:

class Foo{

  constructor(){

    foo = 55  // 严格模式下是不被允許的

  }

}

const foo = new Foo()

3.class的所有方法(包含静态方法)都是不可枚举的

es5:

// 引用一个未声明的变量
function State() {
  this.state = 42;
}
State.answer = function() {
  return 42;
};
State.prototype.print = function() {
  console.log(this.state);
};
const stateKeys = Object.keys(State); // ['answer']
const stateProtoKeys = Object.keys(State.prototype); // ['print']
 
es6:
class Foo {
  constructor() {
    this.foo = 42;
  }
  static answer() {
    return 42;
  }
  print() {
    console.log(this.foo);
  }
}
const fooKeys = Object.keys(Foo); // []
const fooProtoKeys = Object.keys(Foo.prototype); // []
 

4.class的所有方法(包含静态方法)都没有原型对象prototype  所以不能通过new来调用

es5:

function State() {
  this.state = 42;
}
State.prototype.print = function() {
  console.log(this.state);
};

const state = new State();
const statePrint = new state.print();  
 
es6:
class Foo {
  constructor() {
    this.foo = 42;
  }
  print() {
    console.log(this.foo);
  }
}
const foo = new Foo();
const fooPrint = new foo.print(); // TypeError: foo.print is not a constructor  // 因为class声明的Foo里的print并没有constructor  因此 不能用new来调用

5.必须用new来调用class

es5:

function State() {
  this.state = 42;
}
const state = State(); // 可以直接调用State
 
es6:
class Foo {
  constructor() {
    this.foo = 42;
  }
}
const foo = Foo(); // TypeError: Class constructor Foo cannot be invoked without 'new'

6.class内部无法重写类名

es5:

function State() {
  State = 'State'; // it's ok
  this.state = 42;
}
const state = new State();
// State: 'State'
// state: State {state: 42}
 
es6:
class Foo {
  constructor() {
    this.foo = 42;
    Foo = 'Fol'; // TypeError: Assignment to constant variable
  }
}
const foo = new Foo();
Foo = 'Fol'; // it's ok
 
原文地址:https://www.cnblogs.com/Aaron1Tall/p/11192248.html