Singleton模式
var User = (function() {
var instance;
function _User(){}
_User.prototype.say = function(){}
function init() {
return new _User()
}
return function() {
if( instance == null) {
instance = init();
}
return instance;
}
})();
下面一種模式,能夠根據執行的環境,來動態的建立不一樣的對象
var User = (function() {
var instance;
function _Cat(){}
_Cat.prototype.say = function(){}
function _Dog(){}
_Dog.prototype.say = function(){}
return function() {
if( instance == null) {
if( window.debug ) {
instance = new _Cat();
} else {
instance = new _Dog();
}
}
return instance;
}
})();
// for use
User()