概述
Ext.extend是Ext的繼承機(jī)制,這個(gè)函數(shù)的代碼相當(dāng)難懂。要明白這個(gè)函數(shù)的代碼,首先要知道這個(gè)函數(shù)如何使用。
使用方式
假設(shè)有個(gè)function名為SuperClass,要實(shí)現(xiàn)一個(gè)子類,名為MyClass。下面的兩種方式都可以實(shí)現(xiàn)這個(gè)功能。

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


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

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);
}
});
輸出結(jié)果為:
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);
}
});
先了解一下最簡單的繼承是如何實(shí)現(xiàn)的:


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函數(shù)中用到了Ext.override,這個(gè)函數(shù)把第二個(gè)參數(shù)中的所有對象復(fù)制到第一個(gè)對象的prototype中。首先貼上Ext.override函數(shù)的代碼:

Ext.override = function(origclass, overrides)
{

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

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

/**//**
* 繼承,并由傳遞的值決定是否覆蓋原對象的屬性
* 返回的對象中也增加了override()函數(shù),用于覆蓋實(shí)例的成員
* @param {Object} subclass 子類,用于繼承(該類繼承了父類所有屬性,并最終返回該對象)
* @param {Object} superclass 父類,被繼承
* @param {Object} overrides (該參數(shù)可選) 一個(gè)對象,將它本身攜帶的屬性對子類進(jìn)行覆蓋
* @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;
};

}();