LoginSignup
14
15

More than 5 years have passed since last update.

Essential JavaScript Design Patterns For Beginners (作者:Addy Osmani)

Last updated at Posted at 2012-12-26

JavaScriptデザインパターン:The Constructor Pattern

JavaScriptの勉強にすごく役に立つので、JavaScriptを勉強したい人にはお勧めです。

※Basic Constructorsのサンプルソース

function Car( model, year, miles ){
   this.model = model;
   this.year    = year;
   this.miles  = miles;
   this.toString = function(){
    return this.model + " has done " + this.miles + " miles";
   };
}

var civic = new Car( "Honda Civic" , 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010 , 5000 );

console.log(civic.toString());
console.log(mondeo.toString());

※Constructors With Prototypesのサンプルソース

function Car( model, year, miles ){
   this.model = model;
   this.year    = year;
   this.miles  = miles;
}

/*
 Note here that we are using Object.prototype.newMethod rather than 
 Object.prototype so as to avoid redefining the prototype object
*/
Car.prototype.toString = function(){
    return this.model + " has done " + this.miles + " miles";
};

var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);

console.log(civic.toString());
console.log(mondeo.toString());

勉強・分析・まとめ:

1.Basic Constructorsについて  

JavaScriptにまだ詳しくない人はnew演算子で関数を呼び出すのを見たら、きっとびっくりするでしょう。正直私も最初はびっくりしました。実はこのnew演算子で呼び出される関数はコンストラクター(constructor)と呼ばれるものです。下記のソース(public ClassName(property)の部分)に示すように、Javaの中のコンストラクターに該当します。Javaのできる人は、下記のソースを対照的に見れば、わかりやすいと思います。

Javaの中のコンストラクター(constructor)
public class className{
    private property;
    public ClassName(property){
        this.property = property;
    }
}

ただ、ちょっとJavaScriptの方は特別ですが、下記のソースで示すようにコンストラクターの中で関数を宣言することもできます。Javaには私はまだ見たことが無いです。JavaScriptコンストラクターで宣言した関数はnewによって生成した各オブジェクトの中に持つようになります。

   this.toString = function(){
    return this.model + " has done " + this.miles + " miles";
   };

2.Constructors With Prototypesについて

上記のBasic Constructorsでは、コンストラクターの中でtoString()関数を定義しました。したがって、newによってオブジェクトが生成された時に、定義されたtoString()関数を持つようになりました。Constructors With Prototypesは上記Basic Constructorsとの違って、コンストラクターの中で関数を定義せず、その代わりにコンストラクターの持っているprototype属性に関数を定義します。JavaScriptはクラスベース継承モデルが実装されておらず、この代わりにprototypeを使います。このコンストラクターのprototype属性で定義した関数は、このコンストラクターにより生成されたオブジェクトの全てからアクセスできます。下記のソースのなかのthisはnewにより生成したオブジェクトを指します。

Car.prototype.toString = function(){
    return this.model + " has done " + this.miles + " miles";
};

※私もまだまだの身ですが、誤情報の発信を防ぐために、上記の記述の中に間違いとかあれば、ご指摘をお願いします。

修正履歴:

2012/03/22 文言の修正 
[実はJavaScriptの中にも継承という概念があります。]⇛JavaScriptはクラスベース継承モデルが実装されておらず、この代わりにプロトタイプを使います。

14
15
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
14
15