<!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>
<script>
// function Person() {
// this.name = '海绵包包'
// }
// Person.prototype.sayHi = function () {
// console.log('hello')
// }
// let instance = null
// function singleton() {
// if (instance === null) {
// instance = new Person()
// }
// return instance
// }
// let p1 = singleton()
// let p2 = singleton()
// console.log(p1 === p2)
// 现在我要改造上面的代码 把真正的构造函数Person和 instance保护起来,
// 顺便把singleton伪装的再好一点 不让别人看出来他不是一个构造函数
function A() {
function Person() {
this.name = 'rose'
}
Person.prototype.sayHi = function () {
console.log('hello')
}
let instance = null
return function singleton() {
if (instance === null) {
instance = new Person()
}
return instance
}
}
let singleton = A()
console.log(singleton)
let p3 = singleton()
let p4 = singleton()
console.log(p3 === p4)
// 继续改造上面的代码
let Person = (function () {
function Person() {
this.name = 'rose'
}
Person.prototype.sayHi = function () {
console.log('hello')
}
let instance = null
return function singleton() {
if (instance === null) {
instance = new Person()
}
return instance
}
})()
let p1 = new Person()
console.log(Person(), 'Person()')
let p2 = new Person()
console.log(p1 === p2, 'p1 === p2')
// new关键字干了什么
</script>
</body>
</html>