-
-
Save ncou/c86897fb69f63050fbd54df28446fd9e to your computer and use it in GitHub Desktop.
JS Class Style Inheriting
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
function inherit(pThis, pBase) { | |
pThis.prototype = Object.create(pBase.prototype); | |
pThis.prototype.constructor = pThis; | |
pThis.prototype.super = pBase.prototype; | |
} | |
function Animal() { | |
this.type = 'animal'; | |
this.num = 34; | |
} | |
Animal.prototype.what = function() { | |
return this.type; | |
} | |
function Dog() { | |
this.super.constructor(); | |
this.type = 'dog'; | |
} | |
inherit(Dog, Animal); | |
function Mut() { | |
this.super.constructor(); | |
this.type = 'Mut'; | |
} | |
inherit(Mut, Dog); | |
var mut = new Mut(); | |
mut.num; | |
> 34 | |
mut.what(); | |
> 'Mut' | |
mut.super.what(); | |
> 'dog' | |
mut.super.num | |
> 34 | |
mut.super.super.what(); | |
> 'animal' | |
mut.num = 55; | |
mut.super.num; | |
> 34 | |
mut.num; | |
> 55 | |
mut.super.super.num = 126; | |
mut.num; | |
> 55 | |
mut.super.num; | |
> 126 // 設定していないからsuperの値を使った。 | |
mut.super.super.num; | |
> 126 | |
var mut2 = new Mut(); | |
mut2.num; | |
> 34 | |
mut2.super.super.num; | |
> 34 // ちゃんとリセットした |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment