1. Class语法
1. 类的写法
class Person {
constructor(name,age){
this.name = name;
this.age = age;
}
say(){//注意,类中的这个方法,不是函数的简写!!!
console.log(this.name,this.age)
}
}
let obj = new Person("kerwin",100)
console.log(obj)
2. getter
和setter
获取属性或方法与设置属性或方法时默认调用
class List{
constructor(ele){
this.element = ele
}
get html(){
console.log('getter')
return this.element.innerHTML
}
set html(arr){
console.log('setter',arr)
this.element.innerHTML = arr.map(item=>`<li>${item}</li>`).join("")
}
}
let obj = new List(document.querySelector("#list"))
obj.html = ['aa','bb','cc']
3. 静态属性和静态方法
class Person {
static name = "Person这个类"
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
console.log(this.name,this.age)
}
static eat(){
console.log("eat")
}
}
let obj = new Person("kerwin",100)
console.log(Person.name)
Person.eat()
4. 继承
ES6 规定,子类必须在
constructor()
方法中调用super()
,否则就会报错。这是因为子类自己的this
对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,添加子类自己的实例属性和方法。如果不调用super()
方法,子类就得不到自己的this
对象。
class Person {
static name = "Person这个类"
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
console.log(this.name,this.age)
}
static eat(){
console.log("eat")
}
}
class Student extends Person{
constructor(name,age,score){
super(name,age)
this.score = score
}
say(){
super.say()
console.log(this.score)
}
static eat(){
super.eat();
console.log("student eat")
}
}
let obj = new Student("kerwin",100,200)
console.log(obj)
obj.say()
Student.eat()
2. 模块化
JavaScript 现在有两种模块。一种是 ES6 模块,简称 ESM;另一种是 CommonJS 模块,简称 CJS。
CommonJS 模块是 Node.js 专用的,与 ES6 模块不兼容。语法上面,两者最明显的差异是,CommonJS 模块使用
require()
和module.exports
,ES6 模块使用import
和export
。
ES6 模块不是对象,而是通过export
命令显式指定输出的代码,再通过import
命令输入。
1. 写法
写法1:
export default A1
import a1 from "./1.js"
export default {a1,a2}
import A from "./1.js"
写法2:
export {A1,A2}
import {A1,A2} from "./1.js"
import {A1 as a1,A2 as a2} from "./1.js"
import * as obj from "./1.js"
export function A1(){
console.log("A1")
}
export function A2(){
console.log("A2")
}
import {A1,A2} from "./1.js"
import {A1 as a1,A2 as a2} from "./1.js"
import * as obj from "./1.js"
混合写法:
export {A1}
export default A2
import A2,{A1} from "./1.js"
2. 示例
// ./js/a.js
function a1(){
console.log('a.js a1')
}
function a2(){
console.log('a.js a2')
}
export function test(){
console.log('a.js test')
}
export default {a1,a2}
// ./js/b.js
function b1(){
console.log('b.js b1')
}
function b2(){
console.log('b.js b2')
}
export function test(){
console.log('b.js test')
}
export {b1}
<body>
<script type="module">
import A from './js/a.js'
import {test as aTest} from './js/a.js'
import {b1,test as bTest} from './js/b.js'
A.a1()
aTest()
b1()
bTest()
A.test()//报错 A.test is not a function
</script>
</body>