1.js实现单例模式
众所周知,万物皆对象,你定义一个函数,或者一个类,他们是函数和类,但同时他们也是对象,所以你可直接给他们加属性
class Filter {
static getinstance() {
Filter.aaa = 'asfdad'
console.log('asdf', Filter, Filter.aaa, typeof Filter)
console.dir(Filter)
}
}
Filter.getinstance()
function fuck() {
console.log('fuck')
}
fuck.h = 10
console.log(fuck.h)
// 万物皆对象,函数,类都可以添加属性
// 实现单例模式
class Shop {
constructor(name) {
this.name = name
}
static getInstance(name) {
if (!Shop.instance) {
// 不存在实例,那就创建实例
Shop.instance = new Shop(name)
}
// 存在,就返回实例
return Shop.instance
// 众所周知,上面这种写法性能是要远远好于下面这种的
// if (!Shop.instance) {
// Shop.instance = new Shop()
// }else {
// return Shop.instance
// }
}
}
let s1 = Shop.getInstance('s1')
let s2 = Shop.getInstance('s2')
// 不用new而是用一个方法,因为new的话一定会有新的实例产生
// 无法控制
// 但是可以用一个方法控制new,没有就new,有就返回这个,不new
console.log(s1, s2)
可以看看这篇博客 https://www.cnblogs.com/yonglin/p/8080836.html
2.js 类实现私有属性 #
众所周知,java中是有私有属性的,实例无法点出来,只能通过其设置的get函数方法获取,于是引发思考,js中有没有呢,js类,实例默认就可以点出来
而如何让属性点不出来呢,有一个符号 # 可以做到
// class #号定义私有属性
class HH {
#a
constructor(name, age) {
this.#a = name
this.b = age
}
getA() {
return this.#a
}
}
let h1 = new HH('asfsaf', 20)
console.log(h1.a, h1.b)//undefined 20
// 可以惊奇的发现a居然点不出来,说明a已经私有
// 那么如何得到?
// 通过定义的方法
console.log(h1.getA())//asfsaf
3.关于一个没太搞懂的this指向问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
Shop/
<script>
console.log('fuck')
const obj = {
x: 1,
a1: () => {
//这里箭头函数使得this指向,指向了外部window
console.log(this, this.x)
},
a2() {
//this指向obj
console.log(this, this.x)
},
a3: function () {
// 把外面的window绑定给了里面
console.log(this, this.x)
}.bind(this),
// }.bind({}),打印得到 {}
// }.bind('asdf'), 打印得到 String =>'asdf'
// 这说明a3在声明的时候this就已经指定是传的这些了,外部怎么调用也不会改变了
a4: function () {
// this指向obj
console.log(this, this.x)
}
}
obj.a1()
obj.a2()
obj.a3()
obj.a4()
console.log('-----------------------')
const shit = {
x: 10,
hh: {
x: 1,
a1: () => {
//这里箭头函数使得this指向,指向了外部window
console.log(this, this.x)
},
a2() {
//this指向obj
console.log(this, this.x)
},
a3: function () {
// 把外面的window绑定给了里面
console.log(this, this.x)
}.bind(this),
a4: function () {
// this指向obj
console.log(this, this.x)
}
}
}
shit.hh.a1()
shit.hh.a2()
shit.hh.a3()
shit.hh.a4()
// let b = shit.hh.a2
// b()
</script>
</body>
</html>