prototype.js

prototype.jsを使わない継承

<script>
var Nabe = function(dasi,yasai){
	this.dasi = dasi;
	this.yasai = yasai;
}
Nabe.prototype = {
	toString : function(){
		var cook = [];
		cook.push(this.dasi, this.yasai);
		return cook.join('/');
	}
}
//var fuguchiri = new Nabe('konbu', 'hakusai');
//alert(fuguchiri);

var Nabe_DX = function(dasi,yasai,main){
	Nabe.apply(this, [dasi, yasai]);
	this.main = main;
}
Nabe_DX.prototype = {
	toString : function(){
		var cook = [];
		cook.push(Nabe.prototype.toString.apply(this), 'メインは' + this.main);
		return cook.join('*');
	}
}
var fuguchiri_dx = new Nabe_DX('konbu', 'hakusai', 'fugu');
alert(fuguchiri_dx);

Nabe.prototype.toString = function(){
	var cook = [];
	cook.push(this.dasi);
	return cook.join('');
}
alert(fuguchiri_dx);
</script>
  • toStringメソッドはオブジェクト共通のメソッドで、(つまり組み込みのメソッド,と言うのでしょうか)オブジェクトを文字列に変換します。
  • 継承も様々な書き方があるようで、もうちょっと掘り下げておきたい感じ

prototype.jsを使った継承その1

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};
  • [104行目]がポイントとなる
<script src="prototype1.6.js"></script>
<script>
var Nabe = Class.create();
Nabe.prototype = {
	initialize : function(dasi, yasai){
		this.dasi = dasi;
		this.yasai = yasai;
	},
	toString : function(){
		var cook = [];
		cook.push(this.dasi, this.yasai);
		return cook.join('/');
	}
}

var Nabe_dx = Class.create();
Object.extend(Nabe_dx.prototype, Nabe.prototype);
for(p in Nabe_dx.prototype){
	alert(p + ' : ' + Nabe_dx.prototype[p]);
}
</script>
  • こうすることで親クラスのプロトタイプを子クラスのプロトタイプにコピーできる。