上一篇整理了es6解构语法相关的一块知识(【ES6系列】解构赋值(整理篇))。这一篇,要整理的是class相关的知识。es6
class就是类,和ES5中的构造函数十分类似,绝大部分功能都是一致的,可是class的写法,能让对象原型的功能更加清晰,更加符合面向对象语言的特色。函数
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.sayPoint = function() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
复制代码
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
sayPoint() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
}
复制代码
一、constructor就是原来构造函数的写法。 二、定义类的方法的时候,并不须要加逗号,也不须要加function post
class的内部全部定义的方法,都是不可枚举的。而原型上面定义的方法都是能够枚举的。ui
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
sayPoint() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
}
Object.keys(Point.prototype); //[]
复制代码
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.sayPoint = function() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
Object.keys(Point.prototype); //['sayPoint']
复制代码
constructor
是类的默认方法,就算不定义,也会有一个空的constructor
。this
class Point {
}
// 等同于
class Point {
constructor() {
}
}
复制代码
class Point {
constructor() {
return Object.create(null);
}
}
new Point() instanceof Point
// false
复制代码
class Point {
constructor() {
return Object.create(null);
}
}
Point();
// Class constructor Point cannot be invoked without 'new'
复制代码
getter和setter就是拦截器,在作某个操做的时候,能够添加一些自定义的东西。spa
class Point{
constructor() {
// ...
}
get x() {
console.log('getter');
}
set x(val) {
console.log(`setter: ${val}`)
}
}
const p = new Point();
p.x = 1;
// setter: 1
p.x
// getter
复制代码
class内部默认就是严格模式。prototype
new Point(); // SyntaxError: Identifier 'Point' has already been declared
class Point{}
复制代码
类是对ES5构造函数的一层封装,因此不少属性都被class继承,包括name这个属性。code
class Point{}
Point.name // Point
复制代码
正常状况下,this的指向都是类的实例。可是当你单独把其中的方法拿出来调用,那么就会发生报错。对象
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
print() {
console.log(this);
console.log(`x: ${this.x},y: ${this.y}`);
}
}
const p = new Point();
let {print} = p;
print();
复制代码
上述例子中,输出的this是undefined。由于this会指向当前函数运行的环境之下,可是class内部定义了严格模式,因此this为undefined。继承
静态方法是指class上的方法不会被实例继承。关键词——static
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static print() {
console.log(this);
console.log(`x: ${this.x},y: ${this.y}`);
}
}
const p = new Point();
p.print(); // p.print is not a function
Point.print(); // x: undefined,y: undefined
复制代码
静态属性并无static这个关键词。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static print() {
console.log(this);
console.log(`x: ${this.x},y: ${this.y}`);
}
}
Point.z = 1;
const p = new Point();
p.z //undefined
复制代码
当一个属性值并无在初始化的时候赋值,咱们能够像下面那么写:
class Point{
constructor() {
this.x = 1;
this.y = 2;
}
}
// 等同于
class Point{
x = 1;
y = 2;
}
复制代码
这一篇整理了class的一些基础语法。下一篇将会整理class的继承相关。