13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでのObejctの作成方法おさらい

Posted at

知らないことが多くて悲しくなってきた

define_object
// オブジェクトを作成する方法
var newObject = {};

var newObject = new Object();

// オブジェクトにキーを割り当てる方法
// ドット構文
newObject.someKey = "Hello World";

// 角括弧構文
newObject["someKey"] = "Hello World";


// ES5に準拠した書き方(まだサポートしていないブラウザも)
// data propertyの定義
Object.defineProperty( newObject, "someKey", {
	value: "hoge hoge",
	writable: true,
	enumerable: true,
	configurable: true
});


// writable : false で書き換え不可
// emutable : false でfor in ループ中に値が現れない
// configuable : false でdelete不可、value以外の属性変更不可


// 簡略化
var defineProp = function(obj, key, value){
	config.value = value;
	Object.defineProperty(obj, key, config);
}

// 使うには
var person = Object.create(null);

// プロパティーでオブジェクトを追加
defineProp(person, "car", "Delorean");
defineProp(person, "dateOfBirth", "1981");

// definePropertiesを使えば複数登録も可能
Object.defineProperties(newObject, {
	someKey: {
		value: "hoge",
		writable: true
	},
	anotherKey: {
		value: "piyo",
		writable: true
	}
});

// 継承できる
var driver = Object.create(person);

defineProp(driver, "topSpeed", "100mph");

console.log(driver.dateOfBirth); // 1981

13
14
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?