- 継承したい
- オーバーライドしたい
- 親のコンストラクタは暗黙に実行したい
という用途でいろいろと試してみたがいいものがなかったので適当に書いた
var C1 = newClass({ initialize: function(){ this.value1 = "foo"; }, getValue1: function(){ return this.value1; } });
で
var C2 = extend(C1, { initialize: function(){ this.value2 = "bar"; }, getValue1: function(){ return "[" + this.value1 + "]"; }, getValue2: function(){ return "[" + this.value2 + "]"; } }); var c1 = new C1(); var c2 = new C2(); c1.getValue1();//foo c2.getValue1();//[foo] c2.getValue2();//[bar]
のようなことをしたかった
以下、作ったnewClassとextend
function newClass(e){ var f = function(){ this.initialize.apply(this, arguments); } f.prototype = e; return f; } function extend(s, e){ var f = function(){ var init = this.initialize; for(var i = 0, i_n = init.length; i < i_n; ++i){ init[i].apply(this, arguments); } } var proto = {}; for(var name in e){ proto[name] = e[name]; } for(var name in s.prototype){ if(proto[name] === void 0){ proto[name] = s.prototype[name]; } } var super_init = s.prototype.initialize; var init; if(super_init){ if( super_init instanceof Array ){ init = super_init.slice(0);//copy }else{ init = [super_init]; } }else{ init = []; } if(e.initialize){ init.push(e.initialize); } proto.initialize = init; f.prototype = proto; return f; }
Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; }
は論外だとして
YUIの
YAHOO.extend = function(subclass, superclass) { var f = function() {}; f.prototype = superclass.prototype; subclass.prototype = new f(); subclass.prototype.constructor = subclass; subclass.superclass = superclass.prototype; if (superclass.prototype.constructor == Object.prototype.constructor) { superclass.prototype.constructor = superclass; } };
は用途に近くて惜しい感じだった
追記
prototype.jsも 1.6からClass.create()で親クラスを指定して継承できるみたい