※ProxyとECMA5が実装されている処理系で動かしてね。
追記:prototypeチェーンにsuperが2つ絡むとループすることに気がついた・・・のだけど、解決法がわからん。superは一回だけでお願いします(これはひどい)。
まぁ、ソースコードはこれだけなんですが。しかしながら、プロパティだとsuperって書いても一応平気なんですね・・・。
Object.defineProperty(Object.prototype, 'super', {
get: function() {
var superProto, method, constructor;
superProto = Object.getPrototypeOf(Object.getPrototypeOf(this));
method = function(rcvr, name) {
return superProto[name].bind(this);
}.bind(this);
constructor = function() {
superProto.constructor.apply(this, arguments);
}.bind(this);
return Proxy.createFunction({get: method}, constructor);
}
});こんな感じで使えます。extendする系のライブラリでも普通に動くと思います。
function A(message) {
this.message = message;
}
function B() {
//super classのコンストラクタを呼ぶ
this.super('hello!');
}
B.prototype = Object.create(A.prototype);
A.prototype.foo = function() {
return '#' + this.message + '#';
};
B.prototype.foo = function() {
//super classのメソッドを呼ぶ
//もちろんcall(this)しなくてもOK
return '(' + this.super.foo() + ')';
};
var b = new B;
b.foo(); // '(#hello!#);'が返ってくる。