在es5中主要是通过构造函数方式和原型方式来定义一个类,在es6中我们可以通过class来定义类。
一、class类必须new调用,不能直接执行。
class类执行的话会报错
而es5中的类和普通函数并没有本质区别,执行肯定是ok的。
二、class类不存在变量提升
es5中的类
es6中的类
图2报错,说明class方式没有把类的定义提升到顶部。
三、class类无法遍历它实例原型链上的属性和方法
function Foo (color) {
this.color = color
}
Foo.prototype.like = function () {
console.log(`like${this.color}`)
}
let foo = new Foo()
for (let key in foo) {
// 原型上的like也被打印出来了
console.log(key) // color、like
}
class Foo {
constructor (color) {
this.color = color
}
like () {
console.log(`like${this.color}`)
}
}
let foo = new Foo('red')
for (let key in foo) {
// 只打印一个color,没有打印原型链上的like
console.log(key) // color
}
四、new.target属性
es6为new命令引入了一个new.target属性,它会返回new命令作用于的那个构造函数。
如果不是通过new调用或Reflect.construct()调用的,new.target会返回undefined
五、class类有static静态方法
static静态方法只能通过类调用,不会出现在实例上;
静态方法包含 this 关键字,这个 this 指的是类,而不是实例
static声明的静态属性和方法都可以被子类继承。
class Foo {
static bar() {
console.log(`this ${this}`)
this.baz(); // 此处的this指向类
}
static baz() {
console.log('hello'); // 不会出现在实例中
}
baz() {
console.log('world');
}
}
let foo = new Foo();
foo.bar() // undefined
foo.baz() // world
Foo.bar() // this Foo hello
for (let key in foo) { console.log(key) } // 打印为空,说明静态static方法以及原型链上的属性和方法都遍历不到,如果在constructor中添加this.a 可以遍历出a属性以及值