The singleton pattern makes sense and I don’t really know how it works, but I just know that new is the same object over and over again to prevent redundancy in the code.
- A constructor has a function inside it, and if you simply new the constructor, you end up generating the same inner function an infinite number of times. However, it would be nice to attach these internal functions to the prototype
- Such as the kind of popover class, singletons and direct switching display position seems to be able to solve
Don’t understand
A constructor that changes the constructor to a singleton pattern
//fn is a constructor, and sigleEle is a function that turns the constructor into a singleton
let sigleEle = function (fn) {
let _sigleEle = null// Used to store objects generated for the first time
return function (. args) {
if (_sigleEle) {//_sigleEle already stores the first generated object by fnfn.call(_sigleEle, ... args)// Use call to change the internal this reference to the original FN instance
return _sigleEle
}
//_sigleEle is empty
_sigleEle = newfn(... args)return _sigleEle
}
}
// constructor
function Student(name){
this.name = name
}
Student.prototype.addAge = function(age){
this.age = age
}
// Change Student to a singleton constructor named singleStudent
let singleStudent = sigleEle(Student)
let st1 = new singleStudent("wangwu")
let st2 = new singleStudent("lisi")
st1.addAge(13)// The method on the prototype can also be used
console.log(st1)
console.log(st1===st2)//true
Copy the code
SigleEle function analysis:
- The sigleEle function uses closures. The _sigleEle variable is not accessible to the outside world
- _sigleEle is used to store the object generated for the first time. The second time new, _sigleEle is returned directly
- _sigleEle = new fn(… Args), where the returned instance of fn is saved. It must be followed by return _sigleEle in order to return st1 instead of singleStudent’s this