Skip to content

Instantly share code, notes, and snippets.

@kyohei8
Created April 18, 2013 08:08
Show Gist options
  • Save kyohei8/5411045 to your computer and use it in GitHub Desktop.
Save kyohei8/5411045 to your computer and use it in GitHub Desktop.
//closure
var setting = (function () {
return {
speed: 100,
doubleSpeed: function () {
return this.speed * 2;
}
}
}());
console.log(setting.speed); //100
console.log(setting.doubleSpeed()); //200
var singleA = setting;
var singleB = setting;
console.log(singleA === singleB); // true
//closure with private
var setting = (function () {
var _speed = 100; //readonly
return {
doubleSpeed: function () {
return _speed * 2;
},
getSpeed: function () {
return _speed;
}
}
}());
console.log(setting.speed); //undefined
console.log(setting.doubleSpeed()); //200
//instance
var setting;
(function () {
var instance;
setting = function () {
if (instance) {
return instance;
}
instance = this;
this.speed = 100;
this.doubleSpeed = function () {
return speed * 2;
};
return instance;
};
}());
console.log(setting().speed); //100
console.log(setting().doubleSpeed()); //200
var singleA = setting();
var singleB = setting();
console.log(singleA === singleB); // true
//instance separate
var setting = (function () {
var instance;
function init() {
// プライベート変数、メソッド
function halfSpeed() {
return _speed / 2;
}
var _speed = 50;
return {
// パブリック変数、メソッド
doubleSpeed: function () {
return this.speed * 2
},
speed: 100
};
};
return {
getInstance: function () {
//instanceがなければ生成
if (!instance) {
instance = init();
}
return instance;
}
};
})();
console.log(setting.getInstance().speed); //100
console.log(setting.getInstance().doubleSpeed()); //200
var singleA = setting.getInstance();
var singleB = setting.getInstance();
console.log(singleA === singleB); // true
//object literal
var setting = {
speed: 100,
doubleSpeed: function () {
return this.speed * 2;
}
}
console.log(setting.speed); //100
console.log(setting.doubleSpeed()); //200
var singleA = setting;
var singleB = setting;
console.log(singleA === singleB); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment