const常量
javascript
const LIMIT = 10;
const OBJ_MAP = {
a: 'A',
A: 'a'
}
1. 不允许重复声明赋值
js
var arg1 = 'a'
arg1 = 'aa'
// 常量 - ES5
Object.defineProperty(window, 'arg2', {
value: 'aaa',
writable: false
})
// ES6
const arg2 = 'aaa'
2. 块级作用域
js
if (true) {
console.log(arg1)
var arg1 = 'aa'
}
console.log(arg1)
if (true) {
const arg1 = 'aa'
}
// dead zone => 先声明赋值 再使用
3. const 和 let
js
// 会被改变的对象,到底用const还是let?
const obj = {
teacher: 'aa',
date: '20240530'
}
obj.teacher = ''
const obj2 = obj
// 1. 栈 + 2. 堆
// 能用const的地方,都用const
// 面试:如何对一个对象进行常量化?
// 破局 - Object.freeze()
Object.freeze(obj)
// 追问:只能冻结根层?
const obj = {
teacher: 'aa',
date: '20240530',
course: {
course1: 'basic',
course2: 'trial'
}
}
function deepFreeze(obj) {
Object.freeze(obj)
(Object.keys(obj) || []).forEach(key => {
if (typeof obj[key] === 'object') {
deepFreeze(obj[key])
}
})
}
deconstruction 解构 - 解开对象结构
js
const obj = {
teacher: 'yy',
course: 'es'
}
const {
teacher,
course
} = obj;
const arr = [1, 2, 3, 4, 5]
const [a, b, c, d, e] = arr;
let a = 1;
let b = 2;
[b, a] = [a, b]
arrow_function 箭头函数
javascript
// 传统函数
function test(a, b) {
return a + b;
}
const test = function(a, b) {
return a + b;
}
const test = (a, b) => {
return a + b;
}
const test = (a, b) => a + b;
const test = x => {}
上下文
javascript
const obj2 = {
teacher: 'aa',
course: 'es',
table: ['black', 'red'],
getTeacher: function() {
return this.teacher;
},
getTable: () => {
// 不存在独立上下文
}
}
class 助力js更加具有面向对象的形式 - 类
js
// 传统类型的对象 - function
function Course(teacher, course) {
this.teacher = teacher
this.course = course
}
Course.prototype.getCourse = function() {
return `teacher is ${this.teacher}`;
}
const course = new Course('aa', 'ES')
const course1 = new Course('aa1', 'ES2')
// ES6
class Course {
constructor(teacher, course) {
this.teacher = teacher
this.course = course
}
getTeacher() {
return ''
}
static getCourse() {}
}
const course = new Course('aa', 'ES')
course.getTeacher()
Course.getCourse()
追问
class 的类型是什么?
Function => Object => null
class的prototype
js
Course.prototype
class 函数对象的属性
js
course.hasOwnProperty('teacher')
js
// 1. 如何建立只读变量
class Course {
constructor(teacher, course) {
this._teacher = teacher
let _course = 'es'
this.getCourse = () => {
return _course
}
}
// get teacher() {
// return this._teacher
// }
}
class Course {
#course = 'es6'
set course(val) {
if (val) {
this.#course = val
}
}
}
// 3. 封装核心 - 适配器模式
// {
// name: {
// value: 'lodash',
// tag: 124,
// name: 'es6'
// }
// }
class utils {
constructor(core) {
this._main = core
this._name = 'myName'
}
get name() {
return {
...this._main.name,
name: `${this._name}`
}
}
set name(val) {
this._name = val
}
}