概述
Ext.extend是Ext的繼承機制,這個函數的代碼相當難懂。要明白這個函數的代碼,首先要知道這個函數如何使用。
使用方式
假設有個function名為SuperClass,要實現一個子類,名為MyClass。下面的兩種方式都可以實現這個功能。

MyClass = Ext.extend(SuperClass,
{ /**//* */ });


Ext.extend(MyClass, SuperClass,
{ /**//* */});
下面來個具體示例:

var a = function(id)
{
this.id = id;
}


a.prototype =
{

tostring : function()
{
return this.id;
}};

b = function(id)
{
b.superclass.constructor.call(this, id);
}


Ext.extend(b, a,
{

tostring : function()
{
return String.format("b:{0}", this.id);
}
});
輸出結果為:
var obj1 = new a("obj1");
alert(obj1.tostring()); //-----obj1
var obj2 = new b("obj2");
alert(obj2.tostring()); //-----b:obj2
或者下面的代碼,可以得到同樣的效果:

var a = function(id)
{
this.id = id;
}


a.prototype =
{

tostring : function()
{
return this.id;
}
};


b = Ext.extend(a,
{

tostring : function()
{
return String.format("b:{0}", this.id);
}
});
先了解一下最簡單的繼承是如何實現的:


function Extend(subFn, superFn)
{
subFn.prototype = new superFn()
subFn.prototype.constructor = subFn
}


function Animal()
{

this.say1 = function()
{
alert("Animal");
}
}


function Tiger()
{

this.say2 = function()
{
alert("Tiger");
}
}
Extend(Tiger,Animal);
var tiger = new Tiger();
tiger.say1();//"Animal"
tiger.say2();//"Tiger"
Ext.extend函數中用到了Ext.override,這個函數把第二個參數中的所有對象復制到第一個對象的prototype中。首先貼上Ext.override函數的代碼:

Ext.override = function(origclass, overrides)
{

if(overrides)
{
var p = origclass.prototype;

for(var method in overrides)
{
p[method] = overrides[method];
} }
}
然后貼上Ext.extend的代碼:

/**//**
* 繼承,并由傳遞的值決定是否覆蓋原對象的屬性
* 返回的對象中也增加了override()函數,用于覆蓋實例的成員
* @param {Object} subclass 子類,用于繼承(該類繼承了父類所有屬性,并最終返回該對象)
* @param {Object} superclass 父類,被繼承
* @param {Object} overrides (該參數可選) 一個對象,將它本身攜帶的屬性對子類進行覆蓋
* @method extend
*/


function extend ()
{
// inline overrides

var io = function(o)
{

for(var m in o)
{
this[m] = o[m];
}
};

return function(sb, sp, overrides)
{

if(typeof sp == 'object')
{
overrides = sp;
sp = sb;

sb = 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 == Object.prototype.constructor)
{
spp.constructor=sp;
}

sb.override = function(o)
{
Ext.override(sb, o);
};
sbp.override = io;
Ext.override(sb, overrides);
return sb;
};

}();