擴展
Code:
復制代碼 代碼如下:
var blogModule = (function (my) {
my.AddPhoto = function () {
//添加內部代碼
};
return my;
}(blogModule));
Say:
將自身傳進方法,然後實現了方法的擴展,有點象零件組裝啊
Code:
復制代碼 代碼如下:
var blogModule = (function (my) {var oldAddPhotoMethod = my.AddPhoto;
my.AddPhoto = function () { // 重載方法,依然可通過oldAddPhotoMethod調用舊的方 }; return my;}(blogModule));
Say:
好處就是可以調用以前的方法。
克隆與繼承
Code:
復制代碼 代碼如下:
var blogModule = (function (old) { var my = {}, key; for (key in old) { if (old.hasOwnProperty(key)) { my[key] = old[key]; } } var oldAddPhotoMethod = old.AddPhoto; my.AddPhoto = function () { // 克隆以後,進行了重寫,當然也可以繼續調用oldAddPhotoMethod }; return my; } (blogModule));
Say:
簡單的克隆實現
跨文件共享私有對象
Code:
復制代碼 代碼如下:
var blogModule = (function (my) { var _private = my._private = my._private || {}, _seal = my._seal = my._seal || function () { delete my._private; delete my._seal; delete my._unseal; }, _unseal = my._unseal = my._unseal || function () { my._private = _private; my._seal = _seal; my._unseal = _unseal; }; return my; } (blogModule || {}));
Say:
blogModule._seal()上鎖,_unseal() 開鎖,實現內部變量的私有化。我認為這樣實現並不是最好的,但是我們可以學習下這個開鎖閉鎖的功能。