class是es6提供的语法糖,主要有几个要点:
一、写法
class a {
static staticProp = ''; // 属性后面加分号,另外这是类的静态属性。也就是定义在构造函数对象上的属性。
static staticFunc () {} //函数后面不加东西,逗号和分号都不用, 另外这是静态方法,也就是直接定义在构造函数对象上的方法。
propA = ''; // 这是实例的属性。和在constructor内部使用this.propA = '' 等效。
constructor () { // 在用new的时候,会执行这个方法。
}
// functions here
func () {} // 不可枚举的function属性。
get propB () { // 可以直接定义getter和setter方法,这个将直接加在属性的descriptor里面。
}
set propB (nval) {
}
// 只要不是用this定义的属性,都是直接定义在原型上的
}
二、和构造函数的异同
- 首先class指向的实际上就是构造函数。
class a {
}
a === a.prototype.constructor; // true
typeof a; // 'function'
- class不能进行单独调用,一定要和new一起使用,构造函数可以直接调用。
class A {
} // 这种写法会自动带一个空的constructor函数。constructor () {}
A() // TypeError: Class constructor A cannot be invoked without 'new'
- 类和构造函数一样可以以表达式的方式创建
let b = class a {
}
let c = function a () {
}
- class不存在提升。也就是存在暂时性死区(不知道这样表达准确不)
let a = new A(); // Reference Error
class A {
constructor () {
}
}
先总结这样
网友评论