オブジェクトリテラル・new Object()【コンストラクタ】
メモ
- Object【オブジェクト】オブジェクトを生成
- new により生成
- オブジェクトリテラルにより生成
構文
- new Object ( [ value ] )
- オブジェクトリテラルについては、オブジェクトリテラル 参照
- value:値
値 作成オブジェクト 省略
null
undefined空のオブジェクト 文字列 String【文字列】オブジェクト Boolean値 Boolean【真偽値】オブジェクト 数値 Number【数値】オブジェクト
オブジェクト
例
console.log(new Object()); // 出力:Object {}
console.log(new Object(null)); // 出力:Object {}
console.log(new Object(undefined)); // 出力:Object {}
console.log(new Object('string')); // 出力:String {length: 6, "string"}
console.log(new Object(true)); // 出力:Boolean {true}
console.log(new Object(123)); // 出力:Number {123}
// プロパティ アクセス
var point = new Object({ x: 10, y: 20 });
console.log(point.x, point['y']); // 出力:10 20
point.x = 100;
point['y'] = 200;
console.log(point.x, point['y']); // 出力:100 200
// オブジェクトリテラル
var undef;
var num = 1234;
var str = 'string';
var bool = true;
var point = { x: 111, y: 222 };
var strNum = 'number-';
var obj = {
undef,
num,
str,
bool,
point,
x:10,
"y": 20,
123: 123456,
['z']: 30,
[strNum + '567']: 567,
log1 : function ( propName ) { console.log(this[propName]); }, // 関数定義
log2 ( propName ) { console.log(this[propName]); }, // 関数定義の省略形
get xValue () { return this.x; }, // ゲッター
set xValue ( value ) { this.x = value; }, // セッター
}
console.log(obj);
// 出力:{
// 123: 123456
// bool: true
// log1: ( propName )
// log2: ( propName )
// num: 1234
// number-567: 567
// point: Object
// x: 111
// y: 222
// str: "string"
// undef: undefined
// x: 10
// xValue: (...)
// get xValue: xValue()
// set xValue: xValue( value )
// y: 20
// z: 30
// }
// 書き込み
obj['x'] = 100;
obj.y = 200;
obj['z'] = 300;
obj[strNum + '567'] = 56789;
obj['123'] = 321;
obj.num = 4321;
obj.str = "STRING";
obj.bool = false;
obj.point.x = 333;
obj.point.y = 444;
console.log(obj);
// 出力:{
// 123: 321
// bool: false
// log1: ( propName )
// log2: ( propName )
// num: 4321
// number-567: 56789
// point: Object
// x: 333
// y: 444
// str: "STRING"
// undef: undefined
// x: 1000
// xValue: (...)
// get xValue: xValue()
// set xValue: xValue( value )
// y: 200
// z: 300
// }
// セッター
obj.xValue = 1000;
// ゲッター
console.log( obj.xValue ); // 出力:1000
// 関数
obj.log1( 'x' ); // 出力:1000
obj.log1( 'y' ); // 出力:200
obj.log2( 'x' ); // 出力:1000
obj.log2( 'y' ); // 出力:200
関連
- ECMAScript 5.1 (英語)
- 15.2.1.1 Object ( [ value ] )
- 15.2.2.1 new Object ( [ value ] )
- 11.1.5 Object Initialiser
- 11.2.1 Property Accessors
- ECMAScript 6.0 (英語)
- 19.1.1 The Object Constructor
- 19.1.1.1 Object ( [ value ] )
- 12.2.6 Object Initializer