尽管类与自定义类型之间有相似性,但仍然要记住一些重要的区别:
1. 类声明不会被提升,这与函数定义不同。类声明的行为与 let 相似,因此在程序的执行
到达声明处之前,类会存在于暂时性死区内。
2. 类声明中的所有代码会自动运行在严格模式下,并且也无法退出严格模式。
3. 类的所有方法都是不可枚举的,这是对于自定义类型的显著变化,后者必须用
Object.defineProperty() 才能将方法改变为不可枚举。
4. 类的所有方法内部都没有 [[Construct]] ,因此使用 new 来调用它们会抛出错误。
5. 调用类构造器时不使用 new ,会抛出错误。
6. 试图在类的方法内部重写类名,会抛出错误。
我们来看一个简单的类。
class Person {
constructor(name) {
this.name = name;
}
sayName () {
return this.name;
}
}
那么根据以上规则,我不得不该写成为
let Person = (function () {//let
"use strict";//严格模式
const Person = function (name) { //类的方法不得重写类名
if (typeof new.target === "undefined") { //必须以new 调用
throw new Error("You should use new to call this function");
} else {
this.name = name;
}
}
Object.defineProperty(Person.prototype, "sayName", {
value: function () {
if (typeof new.target !== "undefined") { //不得以new 调用
throw new Error("You shouldn't use new to call this function!");
}
return this.name
},
enumerable: false, //不可枚举
writable: true,
configurable: true
})
return Person;
})();
所以用es6的语法非常简单。