<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JS最佳实践——单例模式</title>
</head>
<body>
</body>
<script type="text/javascript">
var app = (function() {
function Singleton(args) {
var args = args || {};
this.name = args.name || 'jone';
this.can = function() {
console.log(args.can || '我会撸代码!');
}
}
var instance;
var _static = {
getInstance: function(args) {
if (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
return _static;
})();
var person = app.getInstance({name:'tang', can: '打篮球!'});
console.log(person.name); // tang
person.can(); // 打篮球
var person2 = app.getInstance({name:'txinz', can: '游泳!'});
console.log(person2.name); // tang
person2.can(); // 打篮球
console.log(person === person2); // true
</script>
</html>