【Yahoo! UI】YUIのyahoo.jsのYAHOO.extend
YUIのv0.11.2を眺めていたら、yahoo.jsにYAHOO.extendが追加されていました。要するに継承の実装なわけですが、prototype.jsのextend のようなシンプルなコピーではなくて、コンストラクタとメソッドをチェーンでつなぐと。うーん、今、試す時間がない、けど、メモ。
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
*
* @param {Function} subclass the object to modify
* @param {Function} superclass the object to inherit
*/
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;
}
};
と思ったら、READMEにちゃんと書いてありました。
0.11.0
* Added YAHOO.extend, which provides an easy way to assign the prototype,
constructor, and superclass properties inheritance properties. It also
prevents the constructor of the superclass from being exectuted twice.
ざっくり訳::0.11.0
* YAHOO.extendを加えました。(YAHOO.extendはプロパティの継承をプロトタイプ、コンストラクタ、およびスーパークラスに割り当てる簡単な方法を提供します)。 それによって、二度スーパークラスのコンストラクタがexectutedされることはありません。
別物ですが、一応、ちなみに、prototype.jsのObject.extend
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
ついでに、私が愛用しているコピー関数copyOj。prototype.jsのObject.extendと等価ですがObject汚染しないただの関数です。
function copyOj(oj,aoj) { for(var i in aoj){ oj[i]=aoj[i] };return oj; }
//applyを使わないのはfor MacIE
ちなみに、JavaScriptでの継承つながりで、こういうのを作っている方もいます。
クラスパッケージ化ツール CPT