如何访问作为命名空间的函数内部变量
把函数做为命名空间已经是当今javascript编程里非常普遍的了。如果你把你的代码包含在一个函数里,那么你的代码里包含的变量和函数对于包含函数是本地的,或者说是局部的,这样则不会扰乱全局作用域。
var value = (function() { // Wrapper function creates a local scope or namespace // your code goes here return value; // Export a value from the namespace})()); // Invoke the wrapper function to run your codevar code = ....; // A string of JS code to evaluatevar f = new Function(code); // Wrap it in a functionf(); // And run the function
return function(s) { return eval(s); };var code = readFile("Set.js"); // A string of JS code to evaluate// Define and invoke a wrapper function with special suffix code.// The return value is a namespace evaluator function and we treat// it as a namespace object.var setns = new Function(code + "return function(s) { return eval(s); };")(); var Set = setns("Set"); // Import the Set function from the namespace.var s = new Set(); // Use the class we just imported// Extract an object containing 3 values from the namespacevar sets = setns('{Set:"Set", BitSet:"BitSet", MultiSet:"MultiSet"}');var bs = new sets.BitSet();/* * Load modules of code by enveloping them in a function and executing * the function: then they don't pollute the global namespace (unless they * assign to undeclared variables, but ES5 strict mode will prevent that.) * The wrapper function we create returns an evaluator function that * evals a string inside the namespace. This evaluator function is the * return value of namespace() and provides read access to the symbols * defined inside the namespace. */function namespace(url) { if (!namespace.cache) namespace.cache = {}; // First call only if (!namespace.cache.hasOwnProperty(url)) { // Only load urls once var code = gettext(url); // Read code from url var f = new Function(code + // Wrap code, add a return value "return function(s) { return eval(s); };"); namespace.cache[url] = f.call({}); // Invoke wrapper, cache evaluator } return namespace.cache[url]; // Return cached evaluator for this namespace} /* Return the text of the specified url, script element or file */function gettext(url) { if (typeof XMLHttpRequest !== "undefined") { // Running in a browser if (url.charAt(0) == '#') { // URL names a script tag var tag = document.getElementById(url.substring(1)); if (!tag || tag.tagName != "SCRIPT") throw new Error("Unknown script " + url); if (tag.src) return gettext(tag.src);// If it has a src attribute else return tag.text; // Otherwise use script content } else { // Load file with Ajax var req = new XMLHttpRequest(); req.open("GET", url, false); // Asynchronous get req.send(null); return req.responseText; // Error handling? } } else if (typeof readFile == "function") return readFile(url); // Rhino else if (typeof snarf == "function") return snarf(url); // Spidermonkey else if (typeof read == "function") return read(url); // V8 else throw new Error("No mechanism to load module text");}