面向对象ES6-封装类

1、ES6直接获取类的静态属性和修改静态属性的值

class Person{
	static num = 10;
	constructor(){
		this.myname = 'joy';
	}
}
Person.staticNum = 20;
console.log(Person.num) // 20

2、静态属性来统计类的实例化次数,防止污染全局

class Person{
	static num = 0;
	constructor(myname){
		this.myname = myname;
		Person.num ++
	}
}
let joy = new Person()
let tom = new Person()
console.log(Person.num) // 2

tips:静态属性是类上面的方法,直接调用
3、ES6私有属性

class Person{
	#weight = '78kg' // #key 表示私有属性
	getWeight(){
		return this.#weight
	}
}
let joy = new Person()
console.log(joy.getWeight())

5、ES6继承

class Dady{
	constructor(hobby) { 
		this.lastName = 'hu'
		this.hobby = hobby
	}
	fn(){
		console.log('父类方法')
	}
}
class Son extends Dady{
	constructor(hobby){
		super(hobby) // 继承父级的方法并且把参数传给父级,执行父级的constructor,并且改变父级函数的指向为自己
		this.name = 'joy'
		// this 一定要调用在super后面
	}
	fullName(){
		return this.lastName + this.name
	}
	fn(){
		super.fn()
		console.log('子类方法')
	}
}
let joy = new Son('swim')
console.log(joy.hobby) // swim
console.log(joy.name) // joy
console.log(joy.lastName) // hu
console.log(joy.fullName()) // hujoy
let tom = new Dady('football') 
console.log(tom.hobby)// football
joy.fn() // '父类方法'  '子类方法'

constructor extends super都是关键字

ESM模块
ES6.js

export {c}
// 输出的得是对象,不能 export c
// export 输出可以是多个
export let b = 14
// export default只能是一个
export default{
	b,
	d
}

html

import'./ES6.js' // import 文件名,直接执行该文件
import * as obj from './ES6.js' // 把ES6.js文件里的所有export内容放到名字会obj的对象里
console.log(obj.b) // 14

import obj,{c} from './ES6.js' 
console.log(obj) // {d: 10}不加{}表示模块里export default的里面的对象
console.log(c) // 20, 加了{}表示模块里export里面该对象的值

import {c as f} from './ES6.js'
console.log(f) // 20 c重命名为f

模块按需导入

document.onclick = function (){
	import ('./ES6.js').then(res => {
 		console.log(res) //res 表示模块里所有export组成的对象
	})
}

document.onclick = async function (){
	let res = await import('./ES6.js')
	console.log(res)
}

以上两个方法都可以异步操作函数,async await更加简单

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值