Created
December 30, 2012 07:43
-
-
Save ynakajima/4411439 to your computer and use it in GitHub Desktop.
継承のテスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
body { background-color: #DDDDDD; font: 30px sans-serif; } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<pre id="console"></pre> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* スーパークラス | |
*/ | |
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