基本
Classの宣言(作成)的なものは、無名関数を代入するのみ。
定義はprototypeにするべし。
var Rect = function(){};
Rect.prototype = {
width:400,
height:300,
getArea:function(){
return this.width * this.height;
}
};
var rect = new Rect();
alert(rect.width);
alert(rect.height);
alert(rect.getArea());
コンストラクタ
コンストラクタは、Classの宣言(作成)時の無名関数に定義する。
var Rect = function(w,h){
this.width = w;
this.height = h;
};
Rect.prototype = {
width:400,
height:300,
getArea:function(){
return this.width * this.height;
}
};
var rect = new Rect(200,200);
alert(rect.width);
alert(rect.height);
alert(rect.getArea());
Classの継承
まずメソッドとかの呼び出しは、
1、インスタンス内を検索
2、プロトタイプ内を検索
の流れになる。
var Hoge = function(){};
Hoge.prototype = {
alert:function(mes){
alert("Hoge.prototype:"+mes);
}
};
var hoge = new Hoge();
hoge.alert("Hello"); //Hoge.prototypeのalert()メソッドを実行
hoge.alert = function(mes){
alert("hoge.instance:"+mes);
};
hoge.alert("Hello"); //hogeインスタンスのalert()メソッドを実行
プロトタイプに親クラスをnewして代入すれば、
親クラスのプロトタイプが子クラスのプロトタイプとなる。
var Parent = function(){};
Parent.prototype = {
test:function(){
alert('Parent.prototype::test');
}
};
var Child = function(){};
Child.prototype = new Parent();
var child = new Child();
child.test();
コメントを残す