时间:2022-04-20 08:58:59 | 栏目:JavaScript代码 | 点击:次
const args='kenneth' const args="kenneth"
es5实现声明常量
Object.defineProperty(window,"args",{ value: ' this is es5', writable: false })
if(true){ const args=123 } console.log(args)
console.log(args) const args=1
var args=123 console.log(window.args) //123 cosnt args1=456 console.log(window.args1) //cosnt不在window中
if(true){ console.log(infor) const infor=123 }
专属报错:
const obj={ id:1, age:18, name:'aaa' } obj.age=19 // cosnt 创建一个对象,对象中的属性可以被改变 //解决:冻结对象,一个被冻结的对象再也不能被修改 Object.freeze() const obj2={ id:2, name:'bbb', age:20, food:['banana','apple'] } Object.freeze(obj2) obj2.age=21 //被Object.freeze()冻结后,不可以改变 obj2.foods[1]='pear' //可以改变 freeze只能冻结根层 嵌套引用类型需要嵌套递归 //实现创建引用类型: function deepFreeze(obj) { Object.freeze(obj); (Object.keys(obj) || []).forEach((key) => { let innerObj = obj[key] if (typeof innerObj === 'object') { deepFreeze(innerObj); } } ) } const tempObj = { id: 23, name: '1', food: ['banana', 'apple'] } deepFreeze(tempObj)
const args='kenneth' const args="kenneth"
es5实现声明常量
Object.defineProperty(window,"args",{ value: ' this is es5', writable: false })
if(true){ const args=123 } console.log(args)
console.log(args) const args=1
var args=123 console.log(window.args) //123 cosnt args1=456 console.log(window.args1) //cosnt不在window中
if(true){ console.log(infor) const infor=123 }
专属报错:
const obj={ id:1, age:18, name:'aaa' } obj.age=19 // cosnt 创建一个对象,对象中的属性可以被改变 //解决:冻结对象,一个被冻结的对象再也不能被修改 Object.freeze() const obj2={ id:2, name:'bbb', age:20, food:['banana','apple'] } Object.freeze(obj2) obj2.age=21 //被Object.freeze()冻结后,不可以改变 obj2.foods[1]='pear' //可以改变 freeze只能冻结根层 嵌套引用类型需要嵌套递归 //实现创建引用类型: function deepFreeze(obj) { Object.freeze(obj); (Object.keys(obj) || []).forEach((key) => { let innerObj = obj[key] if (typeof innerObj === 'object') { deepFreeze(innerObj); } } ) } const tempObj = { id: 23, name: '1', food: ['banana', 'apple'] } deepFreeze(tempObj)