class类
- class(类声明)
- 重复声明一个类会引起类型错误。
- 类表达式定义一个类后再声明一个类同样会报错
- constructor 创建 和 初始化 class创建对象的特殊方法,一个类中只能有 一个 构造方法constructor
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
let polygon = new Polygon(171, 20);
console.log(polygon) //Polygon {name: 'Polygon', height: 171, width: 20}
// 重复定义
class Polygon{} //Uncaught SyntaxError: Identifier 'Polygon' has already been declared
// 静态方法
class Example{
static sum(a, b) {
console.log(a+b);
}
}
Example.sum(1, 2); // 3
// 原型方法
class Example {
sum(a, b) {
console.log(a + b);
}
}
let exam = new Example();
exam.sum(1, 2); // 3
- super关键字 至多出现 一次
- 必须在使用 this 关键字之前使用
- super关键字 也可以用来调用父对象上的函数。
- extends ,用来创建一个子类继承另一个类
class Person {
constructor(name) {
this.name = name;
this.sex = "男";
}
}
class Student extends Person {
constructor(name, age) {
super(name);
this.age = age;
}
}
let s = new Student("张三", 11);
console.log(s.name);
console.log(s.age);
console.log(s.sex);
- getter / setter
class Square extends Polygon {
constructor(length) {
// 在这里, 它调用了父类的构造函数, 并将 length 提供给 Polygon 的"width"和"height"
super(length, length);
// 注意: 在派生类中, 必须先调用 super() 才能使用 "this"。
// 忽略这个,将会导致一个引用错误。
this.name = '正方形';
}
get area () {
return this.height * this.width;
}
set area(value) {
// 注意:不能使用 this.area = value 为area赋值
// 否则会导致循环call setter方法导致爆栈
this._area = value;
}
}
let category = new Square(100)
console.log(category) // Square {name: '正方形', height: 100, width: 100}
export 与 import
- 除export default外,导出的函数什么和类声明都必须要有名称
- import命令会提升到整个模块的头部,首先执行。
- 模块导入导出各种类型的变量,如字符串,数值,函数,类。
export导出
test.js
function f1 ()
{
console.log("函数1: functino 1")
}
let b =
{
name:"test_one"
}
let str = "hell绿绿绿"
export {
f1,b,str
}
demo.html
<script type="module">
import {f1,b,str} from "./demo.js";
console.log(f1,b,str)
</script>
export default导出
test1.js
const demo = {
name: '张三',
age: 18,
devement: '编程'
}
export default demo
demo1.html
<script type="module">
// 不需要加{}, 使用任意变量接收
import demo from "./test3.js";
console.log(demo)
</script>
as的用法
test.js
function f1 ()
{
console.log("函数1: functino 1")
}
let b =
{
name:"test_one"
}
let str = "hell绿绿绿"
export {
f1,b,str
}
// 或者
export {
f1 as fun1,
b as b1,
str as strs
}
demo.html
<script type="module">
import * as test from "./demo.js";
import { fun1, b1, strs} from "./test.js";
console.log(test)
console.log(fun1, b1, strs)
</script>