Onga inc

subtitle

js_design_constructor

Constructorパターン

もっとも簡単に利用できるパターンだと思います。
属性のて定義とメソッドの定義を切り離して設定する事ができます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// コンストラクタを定義する
function Person(name, age) {
this.name = name;
this.age = age;
}

// プロトタイプを拡張してgetNameというメソッドを追加
Person.prototype.getName = function() {
return this.name;
}


// new キーワードをつけてインスタンスを生成する
var person = new Person('mike', 20);
console.log(person.getName()); // John
1
2
3
4
5
6
// プロトタイプを変更
Person.prototype.getName = function() {
return 'Hello! ' + this.name;
}

console.log(person.getName()); // Hello! John

Onga

A designer, developer and entrepreneur. Spends his time travelling the world with a bag of kites. Likes journalism and publishing platforms.

Comments