Skip to content

Instantly share code, notes, and snippets.

@ynakajima
Created December 30, 2012 07:43
Show Gist options
  • Save ynakajima/4411439 to your computer and use it in GitHub Desktop.
Save ynakajima/4411439 to your computer and use it in GitHub Desktop.
継承のテスト
body { background-color: #DDDDDD; font: 30px sans-serif; }
<pre id="console"></pre>
/**
* スーパークラス
*/
var Parent = function(text) {
this.text = "";
this.setText(text);
};
Parent.prototype.alert = function() {
$('#console').append(this.text + "\n");
};
Parent.prototype.setText = function(text) {
this.text = text;
};
/**
* サブクラス
*/
var Child = function(text) {
Parent.call(this, text);
};
// スーパークラスを継承
Child.prototype = new Parent();
// オーバーライド
Child.prototype.setText = function(text) {
// スーパークラスのメソッドを適用
var _super = Parent.prototype;
// 処理を追加
_super.setText.call(this, text);
this.text += ", world.";
};
/**
* サブクラスのサブクラス
*/
var GrandChild = function(text) {
Child.call(this, text);
};
// 継承
GrandChild.prototype = new Child();
// オーバーライド
GrandChild.prototype.setText = function(text) {
// 継承元クラスのメソッドを適用
var _super = Child.prototype;
_super.setText.call(this, text);
// 処理を追加
this.text += '..';
};
GrandChild.prototype.alert = function(text) {
// 継承元クラスのメソッドを適用
Child.prototype.alert.call(this, text);
// 処理を追加
$("<span>" + this.text + "</span>/n").
css({color: 'red'}).
appendTo($('#console'));
};
/**
* 実行
*/
$(function() {
var parent = new Parent('hello');
parent.alert();
var child = new Child('hello');
child.alert();
var grandcChild = new GrandChild('hello');
grandcChild.alert();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment