- Objective:
- Breadcrumb:
# 概念阐释
## 语义
类是一系列具体对象的模板,可以减少复制代码和调试时间。
## 语法
```js
class Name = {...}
```
# 实例
- 1个对象只能指向一只狗
```js
let halley = {
_name: 'Halley',
_behavior: 0,
get name() {
return this._name;
},
get behavior() {
return this._behavior;
},
incrementBehavior() {
this._behavior++;
}
}
```
- 类可以是所有狗这个对象的模板
```js
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior ++;
}
}
```
- 创建名为“Halley”的狗的对象
```js
const halley = new Dog('Halley');
console.log(halley.name); // Print name value to console
console.log(halley.behavior); // Print behavior value to console
halley.incrementBehavior(); // Add one to behavior
console.log(halley.name); // Print name value to console
console.log(halley.behavior); // Print behavior value to console
```
# 相关内容
对象和变量的语法很像,类和对象的语法很像。但类中任何地方都没有**逗号**。
# 问题
# 问题答案
# 参考资料
[类-MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/constructor)