JavaScriptデザインパターン:The Creational Pattern
JavaScriptの勉強にすごく役に立つので、JavaScriptを勉強したい人にはお勧めです。
※The Creational Patternのサンプルソース
//
// Each of the following will create a new empty object
//
var newObject = {}; // or
var newObject = Object.create(null); // or
var newObject = new Object();
// Where the 'Object' constructor creates an object wrapper for
// a specific value, or where no value is passed will create an
// empty object and return it
// There are then a number of ways in which keys and values can
// be assigned to the object including:
newObject.someKey = 'Hello World';
newObject['someKey'] = 'Hello World';
// We can also define new properties on objects as follows,
// should you require more granular configuration capabilities
// (Thanks to Yehuda Katz for the less verbose version of this)
var man = Object.create(null);
// Properties can also be writable, enumerable and configurable
var config = {
writable: true,
enumerable: true,
configurable: true
};
// Short-hand to use Object.defineProperty to add new properties
// with additional configuration
var defineProp = function ( obj, key, value ){
config.value = value;
Object.defineProperty(obj, key, config);
}
defineProp( man, 'car', 'Delorean' );
defineProp( man, 'dob', '1981' );
defineProp( man, 'beard', false );
// And as we'll see a little later, this can even be used for inheritance
// like this..
var driver = Object.create( man );
defineProp (driver, 'topSpeed', '100mph');
driver.topSpeed // 100mph
勉強・分析・まとめ:
1.最初の3Stepで示したのは、emptyオブジェクトを作成する3つの方法です。
一番目の書き方がシンプルでカッコイイので、個人的には一番好きです。
emptyオブジェクトの作成方法その1
var newObject = {}; // or
emptyオブジェクトの作成方法その2
var newObject = Object.create(null); // or
emptyオブジェクトの作成方法その3
var newObject = new Object();
2.オブジェクトへ属性と値の設定方法を4つ示しています。
オブジェクトへ属性と値の設定方法その1
newObject.someKey = 'Hello World';
オブジェクトへ属性と値の設定方法その2
newObject['someKey'] = 'Hello World';
オブジェクトへ属性と値の設定方法その3
// 注意点:ここで引数として渡しているconfigはvalue属性を持つobjectである必要があります。
Object.defineProperty(obj, key, config);
オブジェクトへ属性と値の設定方法その4
//オブジェクトの属性をまとめて初期化する時に使うと便利ですね。
var config = {
writable: true,
enumerable: true,
configurable: true
};
修正履歴:
2012/03/22 Object.defineProperty(obj, key, config)
を使用時の注意点を追加した。