JavaScript命名空间是什么
命名空间是什么?
命名空间本质上是一个普通的对象 将有关联性的变量和函数封装起来看,做为该对象的属性或方法
命名空间有什么作用
解决变量污染的问题
变量污染: 占用某个变量导致后续无法使用此变量(标识)的问题
例如
多人写作开发写了相同的变量名引起冲突
let obj = {
name: '秦始皇',
age: 18,
say: function () {
console.log('我是秦始皇')
}
}
// 使用命名空间
console.log(`我是${obj.name},我今年${obj.age},${obj.say()}`)
封装一个自己的日期命名空间对象
// date是一个命名空间
let date = {
author: '秦始皇',
date: new Date(),
getYear: function () {
return this.date.getFullYear() + 1
},
getMonth : function () {
return this.date.getMonth() + 1
}
}
// 使用封装的命名空间
document.write(`今年是: ${date.getYear()}年${date.getMonth}月`)
为社么要封装一个日期命名空间对象
1.多人协作开发时,命名会冲突
2.如果每个人都要使用 每个人都要 new Date() 节省代码