// Everything returned in the object literal is public, but can access the // members in the closure created above. return { // Public method. stringToArray: function(str, delimiter, stripWS) { if(stripWS) { str = stripWhitespace(str); } var outputArray = stringSplit(str, delimiter); // 这里不再使用 this. 或 GiantCorp.DataParser. 这些前缀只用于访问单例对象的公用属性 return outputArray; } }; })(); // Invoke the function and assign the returned object literal to // GiantCorp.DataParser.
/* General skeleton for a lazy loading singleton, step 1. */
MyNamespace.Singleton = (function() {
functionconstructor() { // All of the normal singleton code goes here. // Private members. var privateAttribute1 = false; var privateAttribute2 = [1, 2, 3];
// The three branches. var standard = { createXhrObject: function() { returnnewXMLHttpRequest(); } }; var activeXNew = { createXhrObject: function() { returnnewActiveXObject('Msxml2.XMLHTTP'); } }; var activeXOld = { createXhrObject: function() { returnnewActiveXObject('Microsoft.XMLHTTP'); } };
})();
/* SimpleXhrFactory singleton, step 2. */
varSimpleXhrFactory = (function() {
// The three branches. var standard = { createXhrObject: function() { returnnewXMLHttpRequest(); } }; var activeXNew = { createXhrObject: function() { returnnewActiveXObject('Msxml2.XMLHTTP'); } }; var activeXOld = { createXhrObject: function() { returnnewActiveXObject('Microsoft.XMLHTTP'); } };
// To assign the branch, try each method; return whatever doesn't fail. var testObject; try { testObject = standard.createXhrObject(); return standard; // Return this if no error was thrown. } catch(e) { try { testObject = activeXNew.createXhrObject(); return activeXNew; // Return this if no error was thrown. } catch(e) { try { testObject = activeXOld.createXhrObject(); return activeXOld; // Return this if no error was thrown. } catch(e) { thrownewError('No XHR object found in this environment.'); } } }
function$() { var elements = []; for (var i = 0, len = arguments.length; i < len; ++i) { var element = arguments[i]; if (typeof element == 'string') { element = document.getElementById(element); } if (arguments.length == 1) { return element; } elements.push(element); } return elements; }
(function() { // Use a private class. function_$(els) { this.elements = []; for (var i = 0, len = els.length; i < len; ++i) { var element = els[i]; if (typeof element == 'string') { element = document.getElementById(element); } this.elements.push(element); } } // The public interface remains the same. window.$ = function() { returnnew_$(arguments); }; })();