本文最早发表于2008-06-07
首入眼帘,代码:
if (overrides) {
for (var i in overrides) {
if (L.hasOwnProperty(overrides, i)) {
subc.prototype[i]=overrides[i];
}
}
L._IEEnumFix(subc.prototype, overrides);
}
}
然后是YUI的儿子,ExtJS:
注:上一个是v2.0的;ExtJS v2.1改进了一点,见:
return function(sb, sp, overrides){
if(typeof sp == 'object'){
overrides = sp;
sp = sb;
sb = overrides.constructor != oc ? overrides.constructor : function(){sp.apply(this, arguments);};
}
var F = function(){}, sbp, spp = sp.prototype;
F.prototype = spp;
sbp = sb.prototype = new F();
sbp.constructor=sb;
sb.superclass=spp;
if(spp.constructor == oc){
spp.constructor=sp;
}
sb.override = function(o){
Ext.override(sb, o);
};
sbp.override = io;
Ext.override(sb, overrides);
sb.extend = function(o){Ext.extend(sb, o);};
return sb;
};
}(),
其实啊,EXT好、YUI也好,它们那一套的继承都源自这个前辈Kevin Lindsey
:
要搞清楚这套继承来龙去脉,这Article就千万不能错过了:
http://kevlindev.com/tutorials/javascript/inheritance/index.htm
问世时间是:Saturday, April 13th, 2002 。
最后,看到一位仁兄的推荐
,来自John
Resig的方案
好像“集百家之所长”,见:
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
还有其他基于类的继承方案,如Lazy Inheritance
、Dean Edwards的Base2,不是说不好,而是很好,好到太复杂了(Lazy
Inheritance的简介像论文似的—题外话),——个人认为过于复杂有点违背JS短小精悍的意思,什么东西过了谱就不行的啦 嘿嘿 所以第一眼就枪毙了。
总结一下..嗯 还没太多的心得,还是台湾
的一位朋友说得好:
無奈
感覺上又回到原始時代,或者說,回到比原始時代更久遠的上古時代,連建構基本的物件架構就有許多的不便,這樣複雜的結構實在有礙思考。想必在Scripting領域的OO或甚至Design
Patten又會發展成另一個Knowledge
Domain吧!過去在其他物件導向語言使用的Patten,硬是要套到這上面來不見得是一件明智的作法,畢竟Script的特性就是如此,與其他語言有一定程度的差別,但也正因為如此,不是Scripting是有缺陷的語言,而是在這個領域的設計及規劃方法,全世界都欠缺足夠的經驗,因此就不像使用
Java或C#那般,可以歡歡喜喜的導入前人歸納的各種設計模式。
注:本文的重点是类继承,如果采用JS原生的“原型”继承 则简单很多——请君勿鄙之,因为存在就是合理。Just take a look 原型继承 by Douglas
Crockford
,比标准方案Prototype = new XX(); Make Sense很多,仅是五六行代码。