let Westros;
(function (Westros) {
var Wall = (function () {
function Wall() {
this.height = 0;
if (Wall._instance)
return Wall._instance;
Wall._instance = this;
}
Wall.prototype.setHeight = function (height) {
this.height = height;
};
Wall.prototype.getHeight = function () {
console.log("Wall is:" + this.height + "miles tall");
};
Wall.getInstance = function () {
if (!Wall._instance){
Wall._instance = new Wall();
}
return Wall._instance;
};
Wall._instance = null;
return Wall;
})();
Westros.Wall = Wall;
})(Westros || (Westros = {}));
缺點
Singletons have gained something of a bad reputation in the last few years. They
are, in effect, glorified global variables. As we’ve discussed, global variables are
ill conceived and the potential cause of numerous bugs. They are also difficult to
test with unit tests as the creation of the instance cannot easily be overridden and
any form of parallelism in the test runner can introduce difficult-to-diagnose race
condition
It isn’t possible to create a clean implementation of the Singleton due to the restrictions on the constructor. This, coupled with the general problems around the Singleton, lead me to suggest that the Singleton pattern should be avoided in JavaScript