4
4

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.

3日目 => デザインパターン(コンストラクタパターン)

Posted at

はじめに

今日はデザインパターン。

コンストラクタパターン

オブジェクトコンストラクタ

特定の型のオブジェクトを作成するために使用

var obj = {};

var obj = new Object();

オブジェクトにキーと値を割り当て

var obj = {};

// ドット構文
obj.name = "SAMPLE";


// 角括弧構文
obj["age"] = 16;


// definePropertyの利用
var obj2 = {};
Object.defineProperty(obj2, "mother", {
  value: "お母さん",
  writable: true, // 値が変更可能かどうか
  enumerable: true, // 指定されたプロパティが列挙可能かどうか
  configurable: true // falseだとdeleteできない・再定義不可
});

for(var key in obj2){
  console.log(key);
}
// enumrableがtrueだと'mother'が出力される


// definePropertiesの利用
var obj4 = {};
Object.defineProperties(obj4, {
  sister: {
    value: "",
    writable: true
  },
  brother: {
    value: "",
    writable: true
  }
});

JavaScriptには基本的にクラスというものがないけど、
コンストラクタ関数を用いることで似たようなことができる、と。

// コンストラクタ関数
function CreateHuman(name, age){
  this.name = name;
  this.age = age;
  this.introduction = function(){
    console.log("私は" + this.name + "。年齢は" + this.age + "歳です。");
  }
}

var hanako = new CreateHuman("花子", 16);
hanako.introduction();
// プロトタイプを利用
CreateHuman.prototype.toString = function(){
  return console.log("私は" + this.name + "。年齢は" + this.age + "歳です。");
}

var taro = new CreateHuman("太郎", 18);
var jiro = new CreateHuman("次郎", 15);

taro.toString();
jiro.toString();
/*
私は太郎。年齢は18歳です。
私は次郎。年齢は15歳です。
*/

おわりに

definePropertyは知らなかった。こんなのもあるのかー。

参考

4
4
0

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?