base.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Bootstrap for the Google JS Library (Closure).
  16. *
  17. * In uncompiled mode base.js will write out Closure's deps file, unless the
  18. * global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to
  19. * include their own deps file(s) from different locations.
  20. *
  21. */
  22. /**
  23. * @define {boolean} Overridden to true by the compiler when --closure_pass
  24. * or --mark_as_compiled is specified.
  25. */
  26. var COMPILED = false;
  27. /**
  28. * Base namespace for the Closure library. Checks to see goog is
  29. * already defined in the current scope before assigning to prevent
  30. * clobbering if base.js is loaded more than once.
  31. *
  32. * @const
  33. */
  34. var goog = goog || {}; // Identifies this file as the Closure base.
  35. /**
  36. * Reference to the global context. In most cases this will be 'window'.
  37. */
  38. goog.global = this;
  39. /**
  40. * @define {boolean} DEBUG is provided as a convenience so that debugging code
  41. * that should not be included in a production js_binary can be easily stripped
  42. * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
  43. * toString() methods should be declared inside an "if (goog.DEBUG)" conditional
  44. * because they are generally used for debugging purposes and it is difficult
  45. * for the JSCompiler to statically determine whether they are used.
  46. */
  47. goog.DEBUG = true;
  48. /**
  49. * @define {string} LOCALE defines the locale being used for compilation. It is
  50. * used to select locale specific data to be compiled in js binary. BUILD rule
  51. * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler
  52. * option.
  53. *
  54. * Take into account that the locale code format is important. You should use
  55. * the canonical Unicode format with hyphen as a delimiter. Language must be
  56. * lowercase, Language Script - Capitalized, Region - UPPERCASE.
  57. * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
  58. *
  59. * See more info about locale codes here:
  60. * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
  61. *
  62. * For language codes you should use values defined by ISO 693-1. See it here
  63. * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
  64. * this rule: the Hebrew language. For legacy reasons the old code (iw) should
  65. * be used instead of the new code (he), see http://wiki/Main/IIISynonyms.
  66. */
  67. goog.LOCALE = 'en'; // default to en
  68. /**
  69. * Creates object stubs for a namespace. The presence of one or more
  70. * goog.provide() calls indicate that the file defines the given
  71. * objects/namespaces. Build tools also scan for provide/require statements
  72. * to discern dependencies, build dependency files (see deps.js), etc.
  73. * @see goog.require
  74. * @param {string} name Namespace provided by this file in the form
  75. * "goog.package.part".
  76. */
  77. goog.provide = function(name) {
  78. if (!COMPILED) {
  79. // Ensure that the same namespace isn't provided twice. This is intended
  80. // to teach new developers that 'goog.provide' is effectively a variable
  81. // declaration. And when JSCompiler transforms goog.provide into a real
  82. // variable declaration, the compiled JS should work the same as the raw
  83. // JS--even when the raw JS uses goog.provide incorrectly.
  84. if (goog.isProvided_(name)) {
  85. throw Error('Namespace "' + name + '" already declared.');
  86. }
  87. delete goog.implicitNamespaces_[name];
  88. var namespace = name;
  89. while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
  90. if (goog.getObjectByName(namespace)) {
  91. break;
  92. }
  93. goog.implicitNamespaces_[namespace] = true;
  94. }
  95. }
  96. goog.exportPath_(name);
  97. };
  98. /**
  99. * Marks that the current file should only be used for testing, and never for
  100. * live code in production.
  101. * @param {string=} opt_message Optional message to add to the error that's
  102. * raised when used in production code.
  103. */
  104. goog.setTestOnly = function(opt_message) {
  105. if (COMPILED && !goog.DEBUG) {
  106. opt_message = opt_message || '';
  107. throw Error('Importing test-only code into non-debug environment' +
  108. opt_message ? ': ' + opt_message : '.');
  109. }
  110. };
  111. if (!COMPILED) {
  112. /**
  113. * Check if the given name has been goog.provided. This will return false for
  114. * names that are available only as implicit namespaces.
  115. * @param {string} name name of the object to look for.
  116. * @return {boolean} Whether the name has been provided.
  117. * @private
  118. */
  119. goog.isProvided_ = function(name) {
  120. return !goog.implicitNamespaces_[name] && !!goog.getObjectByName(name);
  121. };
  122. /**
  123. * Namespaces implicitly defined by goog.provide. For example,
  124. * goog.provide('goog.events.Event') implicitly declares
  125. * that 'goog' and 'goog.events' must be namespaces.
  126. *
  127. * @type {Object}
  128. * @private
  129. */
  130. goog.implicitNamespaces_ = {};
  131. }
  132. /**
  133. * Builds an object structure for the provided namespace path,
  134. * ensuring that names that already exist are not overwritten. For
  135. * example:
  136. * "a.b.c" -> a = {};a.b={};a.b.c={};
  137. * Used by goog.provide and goog.exportSymbol.
  138. * @param {string} name name of the object that this file defines.
  139. * @param {*=} opt_object the object to expose at the end of the path.
  140. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  141. * is |goog.global|.
  142. * @private
  143. */
  144. goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
  145. var parts = name.split('.');
  146. var cur = opt_objectToExportTo || goog.global;
  147. // Internet Explorer exhibits strange behavior when throwing errors from
  148. // methods externed in this manner. See the testExportSymbolExceptions in
  149. // base_test.html for an example.
  150. if (!(parts[0] in cur) && cur.execScript) {
  151. cur.execScript('var ' + parts[0]);
  152. }
  153. // Certain browsers cannot parse code in the form for((a in b); c;);
  154. // This pattern is produced by the JSCompiler when it collapses the
  155. // statement above into the conditional loop below. To prevent this from
  156. // happening, use a for-loop and reserve the init logic as below.
  157. // Parentheses added to eliminate strict JS warning in Firefox.
  158. for (var part; parts.length && (part = parts.shift());) {
  159. if (!parts.length && goog.isDef(opt_object)) {
  160. // last part and we have an object; use it
  161. cur[part] = opt_object;
  162. } else if (cur[part]) {
  163. cur = cur[part];
  164. } else {
  165. cur = cur[part] = {};
  166. }
  167. }
  168. };
  169. /**
  170. * Returns an object based on its fully qualified external name. If you are
  171. * using a compilation pass that renames property names beware that using this
  172. * function will not find renamed properties.
  173. *
  174. * @param {string} name The fully qualified name.
  175. * @param {Object=} opt_obj The object within which to look; default is
  176. * |goog.global|.
  177. * @return {?} The value (object or primitive) or, if not found, null.
  178. */
  179. goog.getObjectByName = function(name, opt_obj) {
  180. var parts = name.split('.');
  181. var cur = opt_obj || goog.global;
  182. for (var part; part = parts.shift(); ) {
  183. if (goog.isDefAndNotNull(cur[part])) {
  184. cur = cur[part];
  185. } else {
  186. return null;
  187. }
  188. }
  189. return cur;
  190. };
  191. /**
  192. * Globalizes a whole namespace, such as goog or goog.lang.
  193. *
  194. * @param {Object} obj The namespace to globalize.
  195. * @param {Object=} opt_global The object to add the properties to.
  196. * @deprecated Properties may be explicitly exported to the global scope, but
  197. * this should no longer be done in bulk.
  198. */
  199. goog.globalize = function(obj, opt_global) {
  200. var global = opt_global || goog.global;
  201. for (var x in obj) {
  202. global[x] = obj[x];
  203. }
  204. };
  205. /**
  206. * Adds a dependency from a file to the files it requires.
  207. * @param {string} relPath The path to the js file.
  208. * @param {Array} provides An array of strings with the names of the objects
  209. * this file provides.
  210. * @param {Array} requires An array of strings with the names of the objects
  211. * this file requires.
  212. */
  213. goog.addDependency = function(relPath, provides, requires) {
  214. if (!COMPILED) {
  215. var provide, require;
  216. var path = relPath.replace(/\\/g, '/');
  217. var deps = goog.dependencies_;
  218. for (var i = 0; provide = provides[i]; i++) {
  219. deps.nameToPath[provide] = path;
  220. if (!(path in deps.pathToNames)) {
  221. deps.pathToNames[path] = {};
  222. }
  223. deps.pathToNames[path][provide] = true;
  224. }
  225. for (var j = 0; require = requires[j]; j++) {
  226. if (!(path in deps.requires)) {
  227. deps.requires[path] = {};
  228. }
  229. deps.requires[path][require] = true;
  230. }
  231. }
  232. };
  233. // NOTE(nnaze): The debug DOM loader was included in base.js as an orignal
  234. // way to do "debug-mode" development. The dependency system can sometimes
  235. // be confusing, as can the debug DOM loader's asyncronous nature.
  236. //
  237. // With the DOM loader, a call to goog.require() is not blocking -- the
  238. // script will not load until some point after the current script. If a
  239. // namespace is needed at runtime, it needs to be defined in a previous
  240. // script, or loaded via require() with its registered dependencies.
  241. // User-defined namespaces may need their own deps file. See http://go/js_deps,
  242. // http://go/genjsdeps, or, externally, DepsWriter.
  243. // http://code.google.com/closure/library/docs/depswriter.html
  244. //
  245. // Because of legacy clients, the DOM loader can't be easily removed from
  246. // base.js. Work is being done to make it disableable or replaceable for
  247. // different environments (DOM-less JavaScript interpreters like Rhino or V8,
  248. // for example). See bootstrap/ for more information.
  249. /**
  250. * @define {boolean} Whether to enable the debug loader.
  251. *
  252. * If enabled, a call to goog.require() will attempt to load the namespace by
  253. * appending a script tag to the DOM (if the namespace has been registered).
  254. *
  255. * If disabled, goog.require() will simply assert that the namespace has been
  256. * provided (and depend on the fact that some outside tool correctly ordered
  257. * the script).
  258. */
  259. goog.ENABLE_DEBUG_LOADER = true;
  260. /**
  261. * Implements a system for the dynamic resolution of dependencies
  262. * that works in parallel with the BUILD system. Note that all calls
  263. * to goog.require will be stripped by the JSCompiler when the
  264. * --closure_pass option is used.
  265. * @see goog.provide
  266. * @param {string} name Namespace to include (as was given in goog.provide())
  267. * in the form "goog.package.part".
  268. */
  269. goog.require = function(name) {
  270. // if the object already exists we do not need do do anything
  271. // TODO(arv): If we start to support require based on file name this has
  272. // to change
  273. // TODO(arv): If we allow goog.foo.* this has to change
  274. // TODO(arv): If we implement dynamic load after page load we should probably
  275. // not remove this code for the compiled output
  276. if (!COMPILED) {
  277. if (goog.isProvided_(name)) {
  278. return;
  279. }
  280. if (goog.ENABLE_DEBUG_LOADER) {
  281. var path = goog.getPathFromDeps_(name);
  282. if (path) {
  283. goog.included_[path] = true;
  284. goog.writeScripts_();
  285. return;
  286. }
  287. }
  288. var errorMessage = 'goog.require could not find: ' + name;
  289. if (goog.global.console) {
  290. goog.global.console['error'](errorMessage);
  291. }
  292. throw Error(errorMessage);
  293. }
  294. };
  295. /**
  296. * Path for included scripts
  297. * @type {string}
  298. */
  299. goog.basePath = '';
  300. /**
  301. * A hook for overriding the base path.
  302. * @type {string|undefined}
  303. */
  304. goog.global.CLOSURE_BASE_PATH;
  305. /**
  306. * Whether to write out Closure's deps file. By default,
  307. * the deps are written.
  308. * @type {boolean|undefined}
  309. */
  310. goog.global.CLOSURE_NO_DEPS;
  311. /**
  312. * A function to import a single script. This is meant to be overridden when
  313. * Closure is being run in non-HTML contexts, such as web workers. It's defined
  314. * in the global scope so that it can be set before base.js is loaded, which
  315. * allows deps.js to be imported properly.
  316. *
  317. * The function is passed the script source, which is a relative URI. It should
  318. * return true if the script was imported, false otherwise.
  319. */
  320. goog.global.CLOSURE_IMPORT_SCRIPT;
  321. /**
  322. * Null function used for default values of callbacks, etc.
  323. * @return {void} Nothing.
  324. */
  325. goog.nullFunction = function() {};
  326. /**
  327. * The identity function. Returns its first argument.
  328. *
  329. * @param {...*} var_args The arguments of the function.
  330. * @return {*} The first argument.
  331. * @deprecated Use goog.functions.identity instead.
  332. */
  333. goog.identityFunction = function(var_args) {
  334. return arguments[0];
  335. };
  336. /**
  337. * When defining a class Foo with an abstract method bar(), you can do:
  338. *
  339. * Foo.prototype.bar = goog.abstractMethod
  340. *
  341. * Now if a subclass of Foo fails to override bar(), an error
  342. * will be thrown when bar() is invoked.
  343. *
  344. * Note: This does not take the name of the function to override as
  345. * an argument because that would make it more difficult to obfuscate
  346. * our JavaScript code.
  347. *
  348. * @type {!Function}
  349. * @throws {Error} when invoked to indicate the method should be
  350. * overridden.
  351. */
  352. goog.abstractMethod = function() {
  353. throw Error('unimplemented abstract method');
  354. };
  355. /**
  356. * Adds a {@code getInstance} static method that always return the same instance
  357. * object.
  358. * @param {!Function} ctor The constructor for the class to add the static
  359. * method to.
  360. */
  361. goog.addSingletonGetter = function(ctor) {
  362. ctor.getInstance = function() {
  363. return ctor.instance_ || (ctor.instance_ = new ctor());
  364. };
  365. };
  366. if (!COMPILED && goog.ENABLE_DEBUG_LOADER) {
  367. /**
  368. * Object used to keep track of urls that have already been added. This
  369. * record allows the prevention of circular dependencies.
  370. * @type {Object}
  371. * @private
  372. */
  373. goog.included_ = {};
  374. /**
  375. * This object is used to keep track of dependencies and other data that is
  376. * used for loading scripts
  377. * @private
  378. * @type {Object}
  379. */
  380. goog.dependencies_ = {
  381. pathToNames: {}, // 1 to many
  382. nameToPath: {}, // 1 to 1
  383. requires: {}, // 1 to many
  384. // used when resolving dependencies to prevent us from
  385. // visiting the file twice
  386. visited: {},
  387. written: {} // used to keep track of script files we have written
  388. };
  389. /**
  390. * Tries to detect whether is in the context of an HTML document.
  391. * @return {boolean} True if it looks like HTML document.
  392. * @private
  393. */
  394. goog.inHtmlDocument_ = function() {
  395. var doc = goog.global.document;
  396. return typeof doc != 'undefined' &&
  397. 'write' in doc; // XULDocument misses write.
  398. };
  399. /**
  400. * Tries to detect the base path of the base.js script that bootstraps Closure
  401. * @private
  402. */
  403. goog.findBasePath_ = function() {
  404. if (goog.global.CLOSURE_BASE_PATH) {
  405. goog.basePath = goog.global.CLOSURE_BASE_PATH;
  406. return;
  407. } else if (!goog.inHtmlDocument_()) {
  408. return;
  409. }
  410. var doc = goog.global.document;
  411. var scripts = doc.getElementsByTagName('script');
  412. // Search backwards since the current script is in almost all cases the one
  413. // that has base.js.
  414. for (var i = scripts.length - 1; i >= 0; --i) {
  415. var src = scripts[i].src;
  416. var qmark = src.lastIndexOf('?');
  417. var l = qmark == -1 ? src.length : qmark;
  418. if (src.substr(l - 7, 7) == 'base.js') {
  419. goog.basePath = src.substr(0, l - 7);
  420. return;
  421. }
  422. }
  423. };
  424. /**
  425. * Imports a script if, and only if, that script hasn't already been imported.
  426. * (Must be called at execution time)
  427. * @param {string} src Script source.
  428. * @private
  429. */
  430. goog.importScript_ = function(src) {
  431. var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
  432. goog.writeScriptTag_;
  433. if (!goog.dependencies_.written[src] && importScript(src)) {
  434. goog.dependencies_.written[src] = true;
  435. }
  436. };
  437. /**
  438. * The default implementation of the import function. Writes a script tag to
  439. * import the script.
  440. *
  441. * @param {string} src The script source.
  442. * @return {boolean} True if the script was imported, false otherwise.
  443. * @private
  444. */
  445. goog.writeScriptTag_ = function(src) {
  446. if (goog.inHtmlDocument_()) {
  447. var doc = goog.global.document;
  448. doc.write(
  449. '<script type="text/javascript" src="' + src + '"></' + 'script>');
  450. return true;
  451. } else {
  452. return false;
  453. }
  454. };
  455. /**
  456. * Resolves dependencies based on the dependencies added using addDependency
  457. * and calls importScript_ in the correct order.
  458. * @private
  459. */
  460. goog.writeScripts_ = function() {
  461. // the scripts we need to write this time
  462. var scripts = [];
  463. var seenScript = {};
  464. var deps = goog.dependencies_;
  465. function visitNode(path) {
  466. if (path in deps.written) {
  467. return;
  468. }
  469. // we have already visited this one. We can get here if we have cyclic
  470. // dependencies
  471. if (path in deps.visited) {
  472. if (!(path in seenScript)) {
  473. seenScript[path] = true;
  474. scripts.push(path);
  475. }
  476. return;
  477. }
  478. deps.visited[path] = true;
  479. if (path in deps.requires) {
  480. for (var requireName in deps.requires[path]) {
  481. // If the required name is defined, we assume that it was already
  482. // bootstrapped by other means.
  483. if (!goog.isProvided_(requireName)) {
  484. if (requireName in deps.nameToPath) {
  485. visitNode(deps.nameToPath[requireName]);
  486. } else {
  487. throw Error('Undefined nameToPath for ' + requireName);
  488. }
  489. }
  490. }
  491. }
  492. if (!(path in seenScript)) {
  493. seenScript[path] = true;
  494. scripts.push(path);
  495. }
  496. }
  497. for (var path in goog.included_) {
  498. if (!deps.written[path]) {
  499. visitNode(path);
  500. }
  501. }
  502. for (var i = 0; i < scripts.length; i++) {
  503. if (scripts[i]) {
  504. goog.importScript_(goog.basePath + scripts[i]);
  505. } else {
  506. throw Error('Undefined script input');
  507. }
  508. }
  509. };
  510. /**
  511. * Looks at the dependency rules and tries to determine the script file that
  512. * fulfills a particular rule.
  513. * @param {string} rule In the form goog.namespace.Class or project.script.
  514. * @return {?string} Url corresponding to the rule, or null.
  515. * @private
  516. */
  517. goog.getPathFromDeps_ = function(rule) {
  518. if (rule in goog.dependencies_.nameToPath) {
  519. return goog.dependencies_.nameToPath[rule];
  520. } else {
  521. return null;
  522. }
  523. };
  524. goog.findBasePath_();
  525. // Allow projects to manage the deps files themselves.
  526. if (!goog.global.CLOSURE_NO_DEPS) {
  527. goog.importScript_(goog.basePath + 'deps.js');
  528. }
  529. }
  530. //==============================================================================
  531. // Language Enhancements
  532. //==============================================================================
  533. /**
  534. * This is a "fixed" version of the typeof operator. It differs from the typeof
  535. * operator in such a way that null returns 'null' and arrays return 'array'.
  536. * @param {*} value The value to get the type of.
  537. * @return {string} The name of the type.
  538. */
  539. goog.typeOf = function(value) {
  540. var s = typeof value;
  541. if (s == 'object') {
  542. if (value) {
  543. // Check these first, so we can avoid calling Object.prototype.toString if
  544. // possible.
  545. //
  546. // IE improperly marshals tyepof across execution contexts, but a
  547. // cross-context object will still return false for "instanceof Object".
  548. if (value instanceof Array) {
  549. return 'array';
  550. } else if (value instanceof Object) {
  551. return s;
  552. }
  553. // HACK: In order to use an Object prototype method on the arbitrary
  554. // value, the compiler requires the value be cast to type Object,
  555. // even though the ECMA spec explicitly allows it.
  556. var className = Object.prototype.toString.call(
  557. /** @type {Object} */ (value));
  558. // In Firefox 3.6, attempting to access iframe window objects' length
  559. // property throws an NS_ERROR_FAILURE, so we need to special-case it
  560. // here.
  561. if (className == '[object Window]') {
  562. return 'object';
  563. }
  564. // We cannot always use constructor == Array or instanceof Array because
  565. // different frames have different Array objects. In IE6, if the iframe
  566. // where the array was created is destroyed, the array loses its
  567. // prototype. Then dereferencing val.splice here throws an exception, so
  568. // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
  569. // so that will work. In this case, this function will return false and
  570. // most array functions will still work because the array is still
  571. // array-like (supports length and []) even though it has lost its
  572. // prototype.
  573. // Mark Miller noticed that Object.prototype.toString
  574. // allows access to the unforgeable [[Class]] property.
  575. // 15.2.4.2 Object.prototype.toString ( )
  576. // When the toString method is called, the following steps are taken:
  577. // 1. Get the [[Class]] property of this object.
  578. // 2. Compute a string value by concatenating the three strings
  579. // "[object ", Result(1), and "]".
  580. // 3. Return Result(2).
  581. // and this behavior survives the destruction of the execution context.
  582. if ((className == '[object Array]' ||
  583. // In IE all non value types are wrapped as objects across window
  584. // boundaries (not iframe though) so we have to do object detection
  585. // for this edge case
  586. typeof value.length == 'number' &&
  587. typeof value.splice != 'undefined' &&
  588. typeof value.propertyIsEnumerable != 'undefined' &&
  589. !value.propertyIsEnumerable('splice')
  590. )) {
  591. return 'array';
  592. }
  593. // HACK: There is still an array case that fails.
  594. // function ArrayImpostor() {}
  595. // ArrayImpostor.prototype = [];
  596. // var impostor = new ArrayImpostor;
  597. // this can be fixed by getting rid of the fast path
  598. // (value instanceof Array) and solely relying on
  599. // (value && Object.prototype.toString.vall(value) === '[object Array]')
  600. // but that would require many more function calls and is not warranted
  601. // unless closure code is receiving objects from untrusted sources.
  602. // IE in cross-window calls does not correctly marshal the function type
  603. // (it appears just as an object) so we cannot use just typeof val ==
  604. // 'function'. However, if the object has a call property, it is a
  605. // function.
  606. if ((className == '[object Function]' ||
  607. typeof value.call != 'undefined' &&
  608. typeof value.propertyIsEnumerable != 'undefined' &&
  609. !value.propertyIsEnumerable('call'))) {
  610. return 'function';
  611. }
  612. } else {
  613. return 'null';
  614. }
  615. } else if (s == 'function' && typeof value.call == 'undefined') {
  616. // In Safari typeof nodeList returns 'function', and on Firefox
  617. // typeof behaves similarly for HTML{Applet,Embed,Object}Elements
  618. // and RegExps. We would like to return object for those and we can
  619. // detect an invalid function by making sure that the function
  620. // object has a call method.
  621. return 'object';
  622. }
  623. return s;
  624. };
  625. /**
  626. * Returns true if the specified value is not |undefined|.
  627. * WARNING: Do not use this to test if an object has a property. Use the in
  628. * operator instead. Additionally, this function assumes that the global
  629. * undefined variable has not been redefined.
  630. * @param {*} val Variable to test.
  631. * @return {boolean} Whether variable is defined.
  632. */
  633. goog.isDef = function(val) {
  634. return val !== undefined;
  635. };
  636. /**
  637. * Returns true if the specified value is |null|
  638. * @param {*} val Variable to test.
  639. * @return {boolean} Whether variable is null.
  640. */
  641. goog.isNull = function(val) {
  642. return val === null;
  643. };
  644. /**
  645. * Returns true if the specified value is defined and not null
  646. * @param {*} val Variable to test.
  647. * @return {boolean} Whether variable is defined and not null.
  648. */
  649. goog.isDefAndNotNull = function(val) {
  650. // Note that undefined == null.
  651. return val != null;
  652. };
  653. /**
  654. * Returns true if the specified value is an array
  655. * @param {*} val Variable to test.
  656. * @return {boolean} Whether variable is an array.
  657. */
  658. goog.isArray = function(val) {
  659. return goog.typeOf(val) == 'array';
  660. };
  661. /**
  662. * Returns true if the object looks like an array. To qualify as array like
  663. * the value needs to be either a NodeList or an object with a Number length
  664. * property.
  665. * @param {*} val Variable to test.
  666. * @return {boolean} Whether variable is an array.
  667. */
  668. goog.isArrayLike = function(val) {
  669. var type = goog.typeOf(val);
  670. return type == 'array' || type == 'object' && typeof val.length == 'number';
  671. };
  672. /**
  673. * Returns true if the object looks like a Date. To qualify as Date-like
  674. * the value needs to be an object and have a getFullYear() function.
  675. * @param {*} val Variable to test.
  676. * @return {boolean} Whether variable is a like a Date.
  677. */
  678. goog.isDateLike = function(val) {
  679. return goog.isObject(val) && typeof val.getFullYear == 'function';
  680. };
  681. /**
  682. * Returns true if the specified value is a string
  683. * @param {*} val Variable to test.
  684. * @return {boolean} Whether variable is a string.
  685. */
  686. goog.isString = function(val) {
  687. return typeof val == 'string';
  688. };
  689. /**
  690. * Returns true if the specified value is a boolean
  691. * @param {*} val Variable to test.
  692. * @return {boolean} Whether variable is boolean.
  693. */
  694. goog.isBoolean = function(val) {
  695. return typeof val == 'boolean';
  696. };
  697. /**
  698. * Returns true if the specified value is a number
  699. * @param {*} val Variable to test.
  700. * @return {boolean} Whether variable is a number.
  701. */
  702. goog.isNumber = function(val) {
  703. return typeof val == 'number';
  704. };
  705. /**
  706. * Returns true if the specified value is a function
  707. * @param {*} val Variable to test.
  708. * @return {boolean} Whether variable is a function.
  709. */
  710. goog.isFunction = function(val) {
  711. return goog.typeOf(val) == 'function';
  712. };
  713. /**
  714. * Returns true if the specified value is an object. This includes arrays
  715. * and functions.
  716. * @param {*} val Variable to test.
  717. * @return {boolean} Whether variable is an object.
  718. */
  719. goog.isObject = function(val) {
  720. var type = typeof val;
  721. return type == 'object' && val != null || type == 'function';
  722. // return Object(val) === val also works, but is slower, especially if val is
  723. // not an object.
  724. };
  725. /**
  726. * Gets a unique ID for an object. This mutates the object so that further
  727. * calls with the same object as a parameter returns the same value. The unique
  728. * ID is guaranteed to be unique across the current session amongst objects that
  729. * are passed into {@code getUid}. There is no guarantee that the ID is unique
  730. * or consistent across sessions. It is unsafe to generate unique ID for
  731. * function prototypes.
  732. *
  733. * @param {Object} obj The object to get the unique ID for.
  734. * @return {number} The unique ID for the object.
  735. */
  736. goog.getUid = function(obj) {
  737. // TODO(arv): Make the type stricter, do not accept null.
  738. // In Opera window.hasOwnProperty exists but always returns false so we avoid
  739. // using it. As a consequence the unique ID generated for BaseClass.prototype
  740. // and SubClass.prototype will be the same.
  741. return obj[goog.UID_PROPERTY_] ||
  742. (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
  743. };
  744. /**
  745. * Removes the unique ID from an object. This is useful if the object was
  746. * previously mutated using {@code goog.getUid} in which case the mutation is
  747. * undone.
  748. * @param {Object} obj The object to remove the unique ID field from.
  749. */
  750. goog.removeUid = function(obj) {
  751. // TODO(arv): Make the type stricter, do not accept null.
  752. // DOM nodes in IE are not instance of Object and throws exception
  753. // for delete. Instead we try to use removeAttribute
  754. if ('removeAttribute' in obj) {
  755. obj.removeAttribute(goog.UID_PROPERTY_);
  756. }
  757. /** @preserveTry */
  758. try {
  759. delete obj[goog.UID_PROPERTY_];
  760. } catch (ex) {
  761. }
  762. };
  763. /**
  764. * Name for unique ID property. Initialized in a way to help avoid collisions
  765. * with other closure javascript on the same page.
  766. * @type {string}
  767. * @private
  768. */
  769. goog.UID_PROPERTY_ = 'closure_uid_' +
  770. Math.floor(Math.random() * 2147483648).toString(36);
  771. /**
  772. * Counter for UID.
  773. * @type {number}
  774. * @private
  775. */
  776. goog.uidCounter_ = 0;
  777. /**
  778. * Adds a hash code field to an object. The hash code is unique for the
  779. * given object.
  780. * @param {Object} obj The object to get the hash code for.
  781. * @return {number} The hash code for the object.
  782. * @deprecated Use goog.getUid instead.
  783. */
  784. goog.getHashCode = goog.getUid;
  785. /**
  786. * Removes the hash code field from an object.
  787. * @param {Object} obj The object to remove the field from.
  788. * @deprecated Use goog.removeUid instead.
  789. */
  790. goog.removeHashCode = goog.removeUid;
  791. /**
  792. * Clones a value. The input may be an Object, Array, or basic type. Objects and
  793. * arrays will be cloned recursively.
  794. *
  795. * WARNINGS:
  796. * <code>goog.cloneObject</code> does not detect reference loops. Objects that
  797. * refer to themselves will cause infinite recursion.
  798. *
  799. * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
  800. * UIDs created by <code>getUid</code> into cloned results.
  801. *
  802. * @param {*} obj The value to clone.
  803. * @return {*} A clone of the input value.
  804. * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
  805. */
  806. goog.cloneObject = function(obj) {
  807. var type = goog.typeOf(obj);
  808. if (type == 'object' || type == 'array') {
  809. if (obj.clone) {
  810. return obj.clone();
  811. }
  812. var clone = type == 'array' ? [] : {};
  813. for (var key in obj) {
  814. clone[key] = goog.cloneObject(obj[key]);
  815. }
  816. return clone;
  817. }
  818. return obj;
  819. };
  820. /**
  821. * Forward declaration for the clone method. This is necessary until the
  822. * compiler can better support duck-typing constructs as used in
  823. * goog.cloneObject.
  824. *
  825. * TODO(brenneman): Remove once the JSCompiler can infer that the check for
  826. * proto.clone is safe in goog.cloneObject.
  827. *
  828. * @type {Function}
  829. */
  830. Object.prototype.clone;
  831. /**
  832. * A native implementation of goog.bind.
  833. * @param {Function} fn A function to partially apply.
  834. * @param {Object|undefined} selfObj Specifies the object which |this| should
  835. * point to when the function is run.
  836. * @param {...*} var_args Additional arguments that are partially
  837. * applied to the function.
  838. * @return {!Function} A partially-applied form of the function bind() was
  839. * invoked as a method of.
  840. * @private
  841. * @suppress {deprecated} The compiler thinks that Function.prototype.bind
  842. * is deprecated because some people have declared a pure-JS version.
  843. * Only the pure-JS version is truly deprecated.
  844. */
  845. goog.bindNative_ = function(fn, selfObj, var_args) {
  846. return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
  847. };
  848. /**
  849. * A pure-JS implementation of goog.bind.
  850. * @param {Function} fn A function to partially apply.
  851. * @param {Object|undefined} selfObj Specifies the object which |this| should
  852. * point to when the function is run.
  853. * @param {...*} var_args Additional arguments that are partially
  854. * applied to the function.
  855. * @return {!Function} A partially-applied form of the function bind() was
  856. * invoked as a method of.
  857. * @private
  858. */
  859. goog.bindJs_ = function(fn, selfObj, var_args) {
  860. if (!fn) {
  861. throw new Error();
  862. }
  863. if (arguments.length > 2) {
  864. var boundArgs = Array.prototype.slice.call(arguments, 2);
  865. return function() {
  866. // Prepend the bound arguments to the current arguments.
  867. var newArgs = Array.prototype.slice.call(arguments);
  868. Array.prototype.unshift.apply(newArgs, boundArgs);
  869. return fn.apply(selfObj, newArgs);
  870. };
  871. } else {
  872. return function() {
  873. return fn.apply(selfObj, arguments);
  874. };
  875. }
  876. };
  877. /**
  878. * Partially applies this function to a particular 'this object' and zero or
  879. * more arguments. The result is a new function with some arguments of the first
  880. * function pre-filled and the value of |this| 'pre-specified'.<br><br>
  881. *
  882. * Remaining arguments specified at call-time are appended to the pre-
  883. * specified ones.<br><br>
  884. *
  885. * Also see: {@link #partial}.<br><br>
  886. *
  887. * Usage:
  888. * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');
  889. * barMethBound('arg3', 'arg4');</pre>
  890. *
  891. * @param {Function} fn A function to partially apply.
  892. * @param {Object|undefined} selfObj Specifies the object which |this| should
  893. * point to when the function is run.
  894. * @param {...*} var_args Additional arguments that are partially
  895. * applied to the function.
  896. * @return {!Function} A partially-applied form of the function bind() was
  897. * invoked as a method of.
  898. * @suppress {deprecated} See above.
  899. */
  900. goog.bind = function(fn, selfObj, var_args) {
  901. // TODO(nicksantos): narrow the type signature.
  902. if (Function.prototype.bind &&
  903. // NOTE(nicksantos): Somebody pulled base.js into the default
  904. // Chrome extension environment. This means that for Chrome extensions,
  905. // they get the implementation of Function.prototype.bind that
  906. // calls goog.bind instead of the native one. Even worse, we don't want
  907. // to introduce a circular dependency between goog.bind and
  908. // Function.prototype.bind, so we have to hack this to make sure it
  909. // works correctly.
  910. Function.prototype.bind.toString().indexOf('native code') != -1) {
  911. goog.bind = goog.bindNative_;
  912. } else {
  913. goog.bind = goog.bindJs_;
  914. }
  915. return goog.bind.apply(null, arguments);
  916. };
  917. /**
  918. * Like bind(), except that a 'this object' is not required. Useful when the
  919. * target function is already bound.
  920. *
  921. * Usage:
  922. * var g = partial(f, arg1, arg2);
  923. * g(arg3, arg4);
  924. *
  925. * @param {Function} fn A function to partially apply.
  926. * @param {...*} var_args Additional arguments that are partially
  927. * applied to fn.
  928. * @return {!Function} A partially-applied form of the function bind() was
  929. * invoked as a method of.
  930. */
  931. goog.partial = function(fn, var_args) {
  932. var args = Array.prototype.slice.call(arguments, 1);
  933. return function() {
  934. // Prepend the bound arguments to the current arguments.
  935. var newArgs = Array.prototype.slice.call(arguments);
  936. newArgs.unshift.apply(newArgs, args);
  937. return fn.apply(this, newArgs);
  938. };
  939. };
  940. /**
  941. * Copies all the members of a source object to a target object. This method
  942. * does not work on all browsers for all objects that contain keys such as
  943. * toString or hasOwnProperty. Use goog.object.extend for this purpose.
  944. * @param {Object} target Target.
  945. * @param {Object} source Source.
  946. */
  947. goog.mixin = function(target, source) {
  948. for (var x in source) {
  949. target[x] = source[x];
  950. }
  951. // For IE7 or lower, the for-in-loop does not contain any properties that are
  952. // not enumerable on the prototype object (for example, isPrototypeOf from
  953. // Object.prototype) but also it will not include 'replace' on objects that
  954. // extend String and change 'replace' (not that it is common for anyone to
  955. // extend anything except Object).
  956. };
  957. /**
  958. * @return {number} An integer value representing the number of milliseconds
  959. * between midnight, January 1, 1970 and the current time.
  960. */
  961. goog.now = Date.now || (function() {
  962. // Unary plus operator converts its operand to a number which in the case of
  963. // a date is done by calling getTime().
  964. return +new Date();
  965. });
  966. /**
  967. * Evals javascript in the global scope. In IE this uses execScript, other
  968. * browsers use goog.global.eval. If goog.global.eval does not evaluate in the
  969. * global scope (for example, in Safari), appends a script tag instead.
  970. * Throws an exception if neither execScript or eval is defined.
  971. * @param {string} script JavaScript string.
  972. */
  973. goog.globalEval = function(script) {
  974. if (goog.global.execScript) {
  975. goog.global.execScript(script, 'JavaScript');
  976. } else if (goog.global.eval) {
  977. // Test to see if eval works
  978. if (goog.evalWorksForGlobals_ == null) {
  979. goog.global.eval('var _et_ = 1;');
  980. if (typeof goog.global['_et_'] != 'undefined') {
  981. delete goog.global['_et_'];
  982. goog.evalWorksForGlobals_ = true;
  983. } else {
  984. goog.evalWorksForGlobals_ = false;
  985. }
  986. }
  987. if (goog.evalWorksForGlobals_) {
  988. goog.global.eval(script);
  989. } else {
  990. var doc = goog.global.document;
  991. var scriptElt = doc.createElement('script');
  992. scriptElt.type = 'text/javascript';
  993. scriptElt.defer = false;
  994. // Note(user): can't use .innerHTML since "t('<test>')" will fail and
  995. // .text doesn't work in Safari 2. Therefore we append a text node.
  996. scriptElt.appendChild(doc.createTextNode(script));
  997. doc.body.appendChild(scriptElt);
  998. doc.body.removeChild(scriptElt);
  999. }
  1000. } else {
  1001. throw Error('goog.globalEval not available');
  1002. }
  1003. };
  1004. /**
  1005. * Indicates whether or not we can call 'eval' directly to eval code in the
  1006. * global scope. Set to a Boolean by the first call to goog.globalEval (which
  1007. * empirically tests whether eval works for globals). @see goog.globalEval
  1008. * @type {?boolean}
  1009. * @private
  1010. */
  1011. goog.evalWorksForGlobals_ = null;
  1012. /**
  1013. * Optional map of CSS class names to obfuscated names used with
  1014. * goog.getCssName().
  1015. * @type {Object|undefined}
  1016. * @private
  1017. * @see goog.setCssNameMapping
  1018. */
  1019. goog.cssNameMapping_;
  1020. /**
  1021. * Optional obfuscation style for CSS class names. Should be set to either
  1022. * 'BY_WHOLE' or 'BY_PART' if defined.
  1023. * @type {string|undefined}
  1024. * @private
  1025. * @see goog.setCssNameMapping
  1026. */
  1027. goog.cssNameMappingStyle_;
  1028. /**
  1029. * Handles strings that are intended to be used as CSS class names.
  1030. *
  1031. * This function works in tandem with @see goog.setCssNameMapping.
  1032. *
  1033. * Without any mapping set, the arguments are simple joined with a
  1034. * hyphen and passed through unaltered.
  1035. *
  1036. * When there is a mapping, there are two possible styles in which
  1037. * these mappings are used. In the BY_PART style, each part (i.e. in
  1038. * between hyphens) of the passed in css name is rewritten according
  1039. * to the map. In the BY_WHOLE style, the full css name is looked up in
  1040. * the map directly. If a rewrite is not specified by the map, the
  1041. * compiler will output a warning.
  1042. *
  1043. * When the mapping is passed to the compiler, it will replace calls
  1044. * to goog.getCssName with the strings from the mapping, e.g.
  1045. * var x = goog.getCssName('foo');
  1046. * var y = goog.getCssName(this.baseClass, 'active');
  1047. * becomes:
  1048. * var x= 'foo';
  1049. * var y = this.baseClass + '-active';
  1050. *
  1051. * If one argument is passed it will be processed, if two are passed
  1052. * only the modifier will be processed, as it is assumed the first
  1053. * argument was generated as a result of calling goog.getCssName.
  1054. *
  1055. * @param {string} className The class name.
  1056. * @param {string=} opt_modifier A modifier to be appended to the class name.
  1057. * @return {string} The class name or the concatenation of the class name and
  1058. * the modifier.
  1059. */
  1060. goog.getCssName = function(className, opt_modifier) {
  1061. var getMapping = function(cssName) {
  1062. return goog.cssNameMapping_[cssName] || cssName;
  1063. };
  1064. var renameByParts = function(cssName) {
  1065. // Remap all the parts individually.
  1066. var parts = cssName.split('-');
  1067. var mapped = [];
  1068. for (var i = 0; i < parts.length; i++) {
  1069. mapped.push(getMapping(parts[i]));
  1070. }
  1071. return mapped.join('-');
  1072. };
  1073. var rename;
  1074. if (goog.cssNameMapping_) {
  1075. rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ?
  1076. getMapping : renameByParts;
  1077. } else {
  1078. rename = function(a) {
  1079. return a;
  1080. };
  1081. }
  1082. if (opt_modifier) {
  1083. return className + '-' + rename(opt_modifier);
  1084. } else {
  1085. return rename(className);
  1086. }
  1087. };
  1088. /**
  1089. * Sets the map to check when returning a value from goog.getCssName(). Example:
  1090. * <pre>
  1091. * goog.setCssNameMapping({
  1092. * "goog": "a",
  1093. * "disabled": "b",
  1094. * });
  1095. *
  1096. * var x = goog.getCssName('goog');
  1097. * // The following evaluates to: "a a-b".
  1098. * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')
  1099. * </pre>
  1100. * When declared as a map of string literals to string literals, the JSCompiler
  1101. * will replace all calls to goog.getCssName() using the supplied map if the
  1102. * --closure_pass flag is set.
  1103. *
  1104. * @param {!Object} mapping A map of strings to strings where keys are possible
  1105. * arguments to goog.getCssName() and values are the corresponding values
  1106. * that should be returned.
  1107. * @param {string=} opt_style The style of css name mapping. There are two valid
  1108. * options: 'BY_PART', and 'BY_WHOLE'.
  1109. * @see goog.getCssName for a description.
  1110. */
  1111. goog.setCssNameMapping = function(mapping, opt_style) {
  1112. goog.cssNameMapping_ = mapping;
  1113. goog.cssNameMappingStyle_ = opt_style;
  1114. };
  1115. /**
  1116. * To use CSS renaming in compiled mode, one of the input files should have a
  1117. * call to goog.setCssNameMapping() with an object literal that the JSCompiler
  1118. * can extract and use to replace all calls to goog.getCssName(). In uncompiled
  1119. * mode, JavaScript code should be loaded before this base.js file that declares
  1120. * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is
  1121. * to ensure that the mapping is loaded before any calls to goog.getCssName()
  1122. * are made in uncompiled mode.
  1123. *
  1124. * A hook for overriding the CSS name mapping.
  1125. * @type {Object|undefined}
  1126. */
  1127. goog.global.CLOSURE_CSS_NAME_MAPPING;
  1128. if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {
  1129. // This does not call goog.setCssNameMapping() because the JSCompiler
  1130. // requires that goog.setCssNameMapping() be called with an object literal.
  1131. goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;
  1132. }
  1133. /**
  1134. * Abstract implementation of goog.getMsg for use with localized messages.
  1135. * @param {string} str Translatable string, places holders in the form {$foo}.
  1136. * @param {Object=} opt_values Map of place holder name to value.
  1137. * @return {string} message with placeholders filled.
  1138. */
  1139. goog.getMsg = function(str, opt_values) {
  1140. var values = opt_values || {};
  1141. for (var key in values) {
  1142. var value = ('' + values[key]).replace(/\$/g, '$$$$');
  1143. str = str.replace(new RegExp('\\{\\$' + key + '\\}', 'gi'), value);
  1144. }
  1145. return str;
  1146. };
  1147. /**
  1148. * Exposes an unobfuscated global namespace path for the given object.
  1149. * Note that fields of the exported object *will* be obfuscated,
  1150. * unless they are exported in turn via this function or
  1151. * goog.exportProperty
  1152. *
  1153. * <p>Also handy for making public items that are defined in anonymous
  1154. * closures.
  1155. *
  1156. * ex. goog.exportSymbol('Foo', Foo);
  1157. *
  1158. * ex. goog.exportSymbol('public.path.Foo.staticFunction',
  1159. * Foo.staticFunction);
  1160. * public.path.Foo.staticFunction();
  1161. *
  1162. * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',
  1163. * Foo.prototype.myMethod);
  1164. * new public.path.Foo().myMethod();
  1165. *
  1166. * @param {string} publicPath Unobfuscated name to export.
  1167. * @param {*} object Object the name should point to.
  1168. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  1169. * is |goog.global|.
  1170. */
  1171. goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {
  1172. goog.exportPath_(publicPath, object, opt_objectToExportTo);
  1173. };
  1174. /**
  1175. * Exports a property unobfuscated into the object's namespace.
  1176. * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);
  1177. * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);
  1178. * @param {Object} object Object whose static property is being exported.
  1179. * @param {string} publicName Unobfuscated name to export.
  1180. * @param {*} symbol Object the name should point to.
  1181. */
  1182. goog.exportProperty = function(object, publicName, symbol) {
  1183. object[publicName] = symbol;
  1184. };
  1185. /**
  1186. * Inherit the prototype methods from one constructor into another.
  1187. *
  1188. * Usage:
  1189. * <pre>
  1190. * function ParentClass(a, b) { }
  1191. * ParentClass.prototype.foo = function(a) { }
  1192. *
  1193. * function ChildClass(a, b, c) {
  1194. * goog.base(this, a, b);
  1195. * }
  1196. * goog.inherits(ChildClass, ParentClass);
  1197. *
  1198. * var child = new ChildClass('a', 'b', 'see');
  1199. * child.foo(); // works
  1200. * </pre>
  1201. *
  1202. * In addition, a superclass' implementation of a method can be invoked
  1203. * as follows:
  1204. *
  1205. * <pre>
  1206. * ChildClass.prototype.foo = function(a) {
  1207. * ChildClass.superClass_.foo.call(this, a);
  1208. * // other code
  1209. * };
  1210. * </pre>
  1211. *
  1212. * @param {Function} childCtor Child class.
  1213. * @param {Function} parentCtor Parent class.
  1214. */
  1215. goog.inherits = function(childCtor, parentCtor) {
  1216. /** @constructor */
  1217. function tempCtor() {};
  1218. tempCtor.prototype = parentCtor.prototype;
  1219. childCtor.superClass_ = parentCtor.prototype;
  1220. childCtor.prototype = new tempCtor();
  1221. childCtor.prototype.constructor = childCtor;
  1222. };
  1223. /**
  1224. * Call up to the superclass.
  1225. *
  1226. * If this is called from a constructor, then this calls the superclass
  1227. * contructor with arguments 1-N.
  1228. *
  1229. * If this is called from a prototype method, then you must pass
  1230. * the name of the method as the second argument to this function. If
  1231. * you do not, you will get a runtime error. This calls the superclass'
  1232. * method with arguments 2-N.
  1233. *
  1234. * This function only works if you use goog.inherits to express
  1235. * inheritance relationships between your classes.
  1236. *
  1237. * This function is a compiler primitive. At compile-time, the
  1238. * compiler will do macro expansion to remove a lot of
  1239. * the extra overhead that this function introduces. The compiler
  1240. * will also enforce a lot of the assumptions that this function
  1241. * makes, and treat it as a compiler error if you break them.
  1242. *
  1243. * @param {!Object} me Should always be "this".
  1244. * @param {*=} opt_methodName The method name if calling a super method.
  1245. * @param {...*} var_args The rest of the arguments.
  1246. * @return {*} The return value of the superclass method.
  1247. */
  1248. goog.base = function(me, opt_methodName, var_args) {
  1249. var caller = arguments.callee.caller;
  1250. if (caller.superClass_) {
  1251. // This is a constructor. Call the superclass constructor.
  1252. return caller.superClass_.constructor.apply(
  1253. me, Array.prototype.slice.call(arguments, 1));
  1254. }
  1255. var args = Array.prototype.slice.call(arguments, 2);
  1256. var foundCaller = false;
  1257. for (var ctor = me.constructor;
  1258. ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
  1259. if (ctor.prototype[opt_methodName] === caller) {
  1260. foundCaller = true;
  1261. } else if (foundCaller) {
  1262. return ctor.prototype[opt_methodName].apply(me, args);
  1263. }
  1264. }
  1265. // If we did not find the caller in the prototype chain,
  1266. // then one of two things happened:
  1267. // 1) The caller is an instance method.
  1268. // 2) This method was not called by the right caller.
  1269. if (me[opt_methodName] === caller) {
  1270. return me.constructor.prototype[opt_methodName].apply(me, args);
  1271. } else {
  1272. throw Error(
  1273. 'goog.base called from a method of one name ' +
  1274. 'to a method of a different name');
  1275. }
  1276. };
  1277. /**
  1278. * Allow for aliasing within scope functions. This function exists for
  1279. * uncompiled code - in compiled code the calls will be inlined and the
  1280. * aliases applied. In uncompiled code the function is simply run since the
  1281. * aliases as written are valid JavaScript.
  1282. * @param {function()} fn Function to call. This function can contain aliases
  1283. * to namespaces (e.g. "var dom = goog.dom") or classes
  1284. * (e.g. "var Timer = goog.Timer").
  1285. */
  1286. goog.scope = function(fn) {
  1287. fn.call(goog.global);
  1288. };