> For the complete documentation index, see [llms.txt](https://1425816423.gitbook.io/my-knowledge-base/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://1425816423.gitbook.io/my-knowledge-base/qian-duan-ji-shu/javascript/es6/es6-class-3a0c0a225a534984aabe9a943c5df975.md).

# ES6 Class 3a0c0a225a534984aabe9a943c5df975

## ES6 Class

status: Draft tags: JavaScript Created time: April 23, 2023 10:52 PM

## 类

### 本质

ECMAScript标准中规定的类本质上的JavaScript构造函数的语法糖。

```tsx
class Application {}

console.log(typeof Application);
// functionction
console.log(Object.getOwnPropertyNames(app.__proto__));
// [ 'constructor' ]
```

### 实例化

实例化的过程中`constructor`会自动执行。并且类一定要被new实例化，如果直接调用，那么将会报错。

```tsx
class Application {}
Application();
// TypeError: Class constructor Application cannot be invoked without 'new'
```

### 实例属性

#### 声明实例属性

在类中定义实例属性有两种方法：

* 在`constructor`中通过`this.`的形式声明
* 直接在类中声明

```tsx
class Application {
  // 第一种写法
	name = "张三";

	constructor() {
    // 第二种写法
		this.age = 18;
	}
}
```

#### getter和setter

在类中可以像在对象中那样定义setter和getter函数。

```tsx
class Application {
	_name = "张三";

	get name() {
		return this._name;
	}

	set name(val) {
		this._name = val;
	}
}

const app = new Application();
console.log(app.name);
// 张三
app.name = 123;
console.log(app.name, app._name);
// 123 123
```

#### 属性表达式

类的属性名可以用表达式

```tsx
class Application {
  constructor(length) {
    // ...
  }

  [methodName]() {
    // ...
  }
}
```

### 原型方法

在类中声明原型方法跟在对象中使用ES6简写方式声明方法类似

```tsx
class Application {
	getName() {}
}
```

这样声明的函数实际上最终会被挂载到实例的原型对象上，作为原型方法。

```tsx
class Application {
	_name = "张三";

	getName() {}
}

const app = new Application();

console.log(Object.getOwnPropertyNames(app.__proto__));
// [ 'constructor', 'getName' ]
```

### 私有属性和私有方法

### 静态属性和静态方法

### 静态块

## 继承
