javascript
JavaScript立即执行函数学习
1.新建對象,方法內變量作用域理解錯誤
var md1 = {count: 0,add: function () {count++;},sub: function () {count--;},show: function () {console.log(count);}};md1.add();md1.add();md1.show();在不加this的情況之下,會試圖與當前對象的作用域內尋找count。如果硬要這樣寫,就必須加入一個全局變量(或者在上級作用域內有count)count,如下。
var count = 100;var md1 = {count: 0,add: function () {count++;},sub: function () {count--;},show: function () {console.log(count);}};md1.add();md1.add();md1.show();當然,正確的方法是如下這樣。
var md1 = {count: 0,add: function () {this.count++;},sub: function () {this.count--;},show: function () {console.log(this.count);}};md1.add();md1.add();md1.show();但是這樣也不好,會暴露count這個理應是私有的成員,可直接在外部代碼之中修改count,如下
var md1 = {count: 0,add: function () {this.count++;},sub: function () {this.count--;},show: function () {console.log(this.count);}};md1.add();md1.add();md1.count = 100;md1.sub();md1.add();md1.show();?
2.立即執行函數式,這種方式可以屏蔽count
var md1 = (function () {var count = 0;var add = function () {count++;};var sub = function () {count--;};var show = function () {console.log(count);};return {add: add,sub: sub,show: show};})();md1.add();md1.add();md1.count = 100;md1.sub();md1.add();md1.show();?
3.放大模式,用于向已有模塊里面添加新的公共成員
var md1 = (function () {var count = 0;var add = function () {count++;};var sub = function () {count--;};var show = function () {console.log(count);};return {add: add,sub: sub,show: show};})();var md2 = (function (md) {md.add2 = function () {md.add();md.add();};return md;})(md1);md1.add();md1.add();md1.sub();md2.add2();md1.show();md2.show();?
4.寬放大模式
var md1 = (function () {var count = 0;var add = function () {count++;};var sub = function () {count--;};var show = function () {console.log(count);};return {add: add,sub: sub,show: show};})();var md2 = (function (md) {md.add2 = function () {md.add();md.add();};return md;})(md1 || {});md1.add();md1.add();md1.sub();md2.add2();md1.show();md2.show();?
獨立性是模塊的重要特點,模塊內部最好不與程序的其他部分直接交互。
為了在模塊內部調用全局變量,必須顯式地將其他變量輸入模塊。
var module1 = (function ($, YAHOO) {
//...
})(jQuery, YAHOO);
上面的module1模塊需要使用jQuery庫和YUI庫,就把這兩個庫(其實是兩個模塊)當作參數輸入module1。這樣做除了保證模塊的獨立性,還使得模塊之間的依賴關系變得明顯。這方面更多的討論,參見Ben Cherry的著名文章《JavaScript Module Pattern: In-Depth》。
這個系列的第二部分,將討論如何在瀏覽器環境組織不同的模塊、管理模塊之間的依賴性。
轉載于:https://www.cnblogs.com/jimaojin/p/7650046.html
總結
以上是生活随笔為你收集整理的JavaScript立即执行函数学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TortoiseGit拉取或推送,输入账
- 下一篇: gradle idea java ssm