標籤:使用 io ar 資料 cti amp sp on new
//使用命名函數運算式實現遞迴var factorial = (function f(num) { if (num <= 1) { return 1; } else { return num * f(num - 1); }});//用作塊級範圍(私人範圍)的匿名函數(function(){ var now = new Date(); if (now.getMonth() == 0 && now.getDate() == 1) { alert("Happy new year!"); }})();//使用建構函式模式實現特權方法的定義function MyObject() { var privateVariable = 10;//私人屬性 function privateFunction() {//私人函數 return false; } //特權方法 this.publicMethod = function() { }}//使用靜態私人變數實現特權方法(function(){ var privateVariable = 10;//私人屬性 function privateFunction() {//私人函數 return false; } //MyObject初始化未經聲明是全域變數 MyObject = function() {}; MyObject.prototype.publicMethod = function() {};})();
/*如果必須建立一個對象並以某些資料對其進行初始化,同時還要公開一下能夠訪問這些私人屬性的方法,那麼就可以使用模組模式。*/var application = function() { var components = new Array(); components.push(new BaseComponent()); return { getComponentCount : function() { return components.length; }, registerComponent : function(component) { if (typeof component == "object") { components.push(component); } } };}
遞迴、閉包、私人變數、特權方法、單例、模組模式(module pattern)