Skip to content

Instantly share code, notes, and snippets.

@ncou
Forked from Moncader/gist:3521832
Created August 17, 2017 13:06
Show Gist options
  • Save ncou/c86897fb69f63050fbd54df28446fd9e to your computer and use it in GitHub Desktop.
Save ncou/c86897fb69f63050fbd54df28446fd9e to your computer and use it in GitHub Desktop.
JS Class Style Inheriting
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