Skip to content

Instantly share code, notes, and snippets.

@Moncader
Created August 30, 2012 02:38
Show Gist options
  • Save Moncader/3521832 to your computer and use it in GitHub Desktop.
Save Moncader/3521832 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