?1 var ?net? = ? new ?Object();//命名空間,防止全局變量的沖突
?2 net.READY_STATE_UNINITIALIZED? = ? 0 ;
?3
?4 net.ContentLoader? = ? function (url,?onload,?onerror) {
?6 ??? this .url? = ?url;
?7 ??? this .req? = ? null ;
?8 ??? this .onload? = ?onload;//保存是方法名
?9 ??? this .onerror? = ?(onerror)? ? ?onerror?:? this .defaultError;
10 ??? this .loadXMLDoc(url);
11 }

12 net.ContentLoader.prototype? = ? {
13 ???loadXMLDoc: function (url) {
15 ??????
16 ?????? try {
?????????????????? var ?loader? = ? this ;//重點!loader為new出來的對象。
????????????????? this .req.onreadystatechange? = ? function () {
20 ?????????? loader.onReadyState.call(loader);//重點!?因為loader為new出來的對象,所以它可以調用對象內部的屬性或方法。應該可以像在catch方法內一樣使用this調用原型內的方法。
21 ?????????????}

23 ????????? }

24 ?????? catch (err) {
26 ?????????? this .onerror.call( this );//同上
27 ??????}

28 ???}

29 ???onReadyState: function () {
31 ?????? var ?req? = ? this .req;
32 ?????? var ?ready? = ?req.readyState;
33 ??????
34 ?????? this .onload.call( this );//this.onload為一個方法名。這樣是調用new出來的對象的回調函數。
35 ??????
36 ?????? this .onerror.call( this );
37 ???}

38 ???defaultError: function () {
40 ??????alert();
41 ???}

42 }

//這樣做,可以把所有的狀態都保存在對象內部,而不是設置一個全局變量。