PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/packages/closure-library/src/main/resources/com/github/urmuzov/closuremaven/closurelibrarypackage/javascript/goog/base.js

https://github.com/urmuzov/closure-maven
JavaScript | 1498 lines | 502 code | 193 blank | 803 comment | 157 complexity | 844271e7d0b1bb8cb146c523976816b7 MD5 | raw file
  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 {*=} opt_returnValue The single value that will be returned.
  330. * @param {...*} var_args Optional trailing arguments. These are ignored.
  331. * @return {?} The first argument. We can't know the type -- just pass it along
  332. * without type.
  333. * @deprecated Use goog.functions.identity instead.
  334. */
  335. goog.identityFunction = function(opt_returnValue, var_args) {
  336. return opt_returnValue;
  337. };
  338. /**
  339. * When defining a class Foo with an abstract method bar(), you can do:
  340. *
  341. * Foo.prototype.bar = goog.abstractMethod
  342. *
  343. * Now if a subclass of Foo fails to override bar(), an error
  344. * will be thrown when bar() is invoked.
  345. *
  346. * Note: This does not take the name of the function to override as
  347. * an argument because that would make it more difficult to obfuscate
  348. * our JavaScript code.
  349. *
  350. * @type {!Function}
  351. * @throws {Error} when invoked to indicate the method should be
  352. * overridden.
  353. */
  354. goog.abstractMethod = function() {
  355. throw Error('unimplemented abstract method');
  356. };
  357. /**
  358. * Adds a {@code getInstance} static method that always return the same instance
  359. * object.
  360. * @param {!Function} ctor The constructor for the class to add the static
  361. * method to.
  362. */
  363. goog.addSingletonGetter = function(ctor) {
  364. ctor.getInstance = function() {
  365. if (ctor.instance_) {
  366. return ctor.instance_;
  367. }
  368. if (goog.DEBUG) {
  369. // NOTE: JSCompiler can't optimize away Array#push.
  370. goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;
  371. }
  372. return ctor.instance_ = new ctor;
  373. };
  374. };
  375. /**
  376. * All singleton classes that have been instantiated, for testing. Don't read
  377. * it directly, use the {@code goog.testing.singleton} module. The compiler
  378. * removes this variable if unused.
  379. * @type {!Array.<!Function>}
  380. * @private
  381. */
  382. goog.instantiatedSingletons_ = [];
  383. if (!COMPILED && goog.ENABLE_DEBUG_LOADER) {
  384. /**
  385. * Object used to keep track of urls that have already been added. This
  386. * record allows the prevention of circular dependencies.
  387. * @type {Object}
  388. * @private
  389. */
  390. goog.included_ = {};
  391. /**
  392. * This object is used to keep track of dependencies and other data that is
  393. * used for loading scripts
  394. * @private
  395. * @type {Object}
  396. */
  397. goog.dependencies_ = {
  398. pathToNames: {}, // 1 to many
  399. nameToPath: {}, // 1 to 1
  400. requires: {}, // 1 to many
  401. // used when resolving dependencies to prevent us from
  402. // visiting the file twice
  403. visited: {},
  404. written: {} // used to keep track of script files we have written
  405. };
  406. /**
  407. * Tries to detect whether is in the context of an HTML document.
  408. * @return {boolean} True if it looks like HTML document.
  409. * @private
  410. */
  411. goog.inHtmlDocument_ = function() {
  412. var doc = goog.global.document;
  413. return typeof doc != 'undefined' &&
  414. 'write' in doc; // XULDocument misses write.
  415. };
  416. /**
  417. * Tries to detect the base path of the base.js script that bootstraps Closure
  418. * @private
  419. */
  420. goog.findBasePath_ = function() {
  421. if (goog.global.CLOSURE_BASE_PATH) {
  422. goog.basePath = goog.global.CLOSURE_BASE_PATH;
  423. return;
  424. } else if (!goog.inHtmlDocument_()) {
  425. return;
  426. }
  427. var doc = goog.global.document;
  428. var scripts = doc.getElementsByTagName('script');
  429. // Search backwards since the current script is in almost all cases the one
  430. // that has base.js.
  431. for (var i = scripts.length - 1; i >= 0; --i) {
  432. var src = scripts[i].src;
  433. var qmark = src.lastIndexOf('?');
  434. var l = qmark == -1 ? src.length : qmark;
  435. if (src.substr(l - 7, 7) == 'base.js') {
  436. goog.basePath = src.substr(0, l - 7);
  437. return;
  438. }
  439. }
  440. };
  441. /**
  442. * Imports a script if, and only if, that script hasn't already been imported.
  443. * (Must be called at execution time)
  444. * @param {string} src Script source.
  445. * @private
  446. */
  447. goog.importScript_ = function(src) {
  448. var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
  449. goog.writeScriptTag_;
  450. if (!goog.dependencies_.written[src] && importScript(src)) {
  451. goog.dependencies_.written[src] = true;
  452. }
  453. };
  454. /**
  455. * The default implementation of the import function. Writes a script tag to
  456. * import the script.
  457. *
  458. * @param {string} src The script source.
  459. * @return {boolean} True if the script was imported, false otherwise.
  460. * @private
  461. */
  462. goog.writeScriptTag_ = function(src) {
  463. if (goog.inHtmlDocument_()) {
  464. var doc = goog.global.document;
  465. doc.write(
  466. '<script type="text/javascript" src="' + src + '"></' + 'script>');
  467. return true;
  468. } else {
  469. return false;
  470. }
  471. };
  472. /**
  473. * Resolves dependencies based on the dependencies added using addDependency
  474. * and calls importScript_ in the correct order.
  475. * @private
  476. */
  477. goog.writeScripts_ = function() {
  478. // the scripts we need to write this time
  479. var scripts = [];
  480. var seenScript = {};
  481. var deps = goog.dependencies_;
  482. function visitNode(path) {
  483. if (path in deps.written) {
  484. return;
  485. }
  486. // we have already visited this one. We can get here if we have cyclic
  487. // dependencies
  488. if (path in deps.visited) {
  489. if (!(path in seenScript)) {
  490. seenScript[path] = true;
  491. scripts.push(path);
  492. }
  493. return;
  494. }
  495. deps.visited[path] = true;
  496. if (path in deps.requires) {
  497. for (var requireName in deps.requires[path]) {
  498. // If the required name is defined, we assume that it was already
  499. // bootstrapped by other means.
  500. if (!goog.isProvided_(requireName)) {
  501. if (requireName in deps.nameToPath) {
  502. visitNode(deps.nameToPath[requireName]);
  503. } else {
  504. throw Error('Undefined nameToPath for ' + requireName);
  505. }
  506. }
  507. }
  508. }
  509. if (!(path in seenScript)) {
  510. seenScript[path] = true;
  511. scripts.push(path);
  512. }
  513. }
  514. for (var path in goog.included_) {
  515. if (!deps.written[path]) {
  516. visitNode(path);
  517. }
  518. }
  519. for (var i = 0; i < scripts.length; i++) {
  520. if (scripts[i]) {
  521. goog.importScript_(goog.basePath + scripts[i]);
  522. } else {
  523. throw Error('Undefined script input');
  524. }
  525. }
  526. };
  527. /**
  528. * Looks at the dependency rules and tries to determine the script file that
  529. * fulfills a particular rule.
  530. * @param {string} rule In the form goog.namespace.Class or project.script.
  531. * @return {?string} Url corresponding to the rule, or null.
  532. * @private
  533. */
  534. goog.getPathFromDeps_ = function(rule) {
  535. if (rule in goog.dependencies_.nameToPath) {
  536. return goog.dependencies_.nameToPath[rule];
  537. } else {
  538. return null;
  539. }
  540. };
  541. goog.findBasePath_();
  542. // Allow projects to manage the deps files themselves.
  543. if (!goog.global.CLOSURE_NO_DEPS) {
  544. goog.importScript_(goog.basePath + 'deps.js');
  545. }
  546. }
  547. //==============================================================================
  548. // Language Enhancements
  549. //==============================================================================
  550. /**
  551. * This is a "fixed" version of the typeof operator. It differs from the typeof
  552. * operator in such a way that null returns 'null' and arrays return 'array'.
  553. * @param {*} value The value to get the type of.
  554. * @return {string} The name of the type.
  555. */
  556. goog.typeOf = function(value) {
  557. var s = typeof value;
  558. if (s == 'object') {
  559. if (value) {
  560. // Check these first, so we can avoid calling Object.prototype.toString if
  561. // possible.
  562. //
  563. // IE improperly marshals tyepof across execution contexts, but a
  564. // cross-context object will still return false for "instanceof Object".
  565. if (value instanceof Array) {
  566. return 'array';
  567. } else if (value instanceof Object) {
  568. return s;
  569. }
  570. // HACK: In order to use an Object prototype method on the arbitrary
  571. // value, the compiler requires the value be cast to type Object,
  572. // even though the ECMA spec explicitly allows it.
  573. var className = Object.prototype.toString.call(
  574. /** @type {Object} */ (value));
  575. // In Firefox 3.6, attempting to access iframe window objects' length
  576. // property throws an NS_ERROR_FAILURE, so we need to special-case it
  577. // here.
  578. if (className == '[object Window]') {
  579. return 'object';
  580. }
  581. // We cannot always use constructor == Array or instanceof Array because
  582. // different frames have different Array objects. In IE6, if the iframe
  583. // where the array was created is destroyed, the array loses its
  584. // prototype. Then dereferencing val.splice here throws an exception, so
  585. // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
  586. // so that will work. In this case, this function will return false and
  587. // most array functions will still work because the array is still
  588. // array-like (supports length and []) even though it has lost its
  589. // prototype.
  590. // Mark Miller noticed that Object.prototype.toString
  591. // allows access to the unforgeable [[Class]] property.
  592. // 15.2.4.2 Object.prototype.toString ( )
  593. // When the toString method is called, the following steps are taken:
  594. // 1. Get the [[Class]] property of this object.
  595. // 2. Compute a string value by concatenating the three strings
  596. // "[object ", Result(1), and "]".
  597. // 3. Return Result(2).
  598. // and this behavior survives the destruction of the execution context.
  599. if ((className == '[object Array]' ||
  600. // In IE all non value types are wrapped as objects across window
  601. // boundaries (not iframe though) so we have to do object detection
  602. // for this edge case
  603. typeof value.length == 'number' &&
  604. typeof value.splice != 'undefined' &&
  605. typeof value.propertyIsEnumerable != 'undefined' &&
  606. !value.propertyIsEnumerable('splice')
  607. )) {
  608. return 'array';
  609. }
  610. // HACK: There is still an array case that fails.
  611. // function ArrayImpostor() {}
  612. // ArrayImpostor.prototype = [];
  613. // var impostor = new ArrayImpostor;
  614. // this can be fixed by getting rid of the fast path
  615. // (value instanceof Array) and solely relying on
  616. // (value && Object.prototype.toString.vall(value) === '[object Array]')
  617. // but that would require many more function calls and is not warranted
  618. // unless closure code is receiving objects from untrusted sources.
  619. // IE in cross-window calls does not correctly marshal the function type
  620. // (it appears just as an object) so we cannot use just typeof val ==
  621. // 'function'. However, if the object has a call property, it is a
  622. // function.
  623. if ((className == '[object Function]' ||
  624. typeof value.call != 'undefined' &&
  625. typeof value.propertyIsEnumerable != 'undefined' &&
  626. !value.propertyIsEnumerable('call'))) {
  627. return 'function';
  628. }
  629. } else {
  630. return 'null';
  631. }
  632. } else if (s == 'function' && typeof value.call == 'undefined') {
  633. // In Safari typeof nodeList returns 'function', and on Firefox
  634. // typeof behaves similarly for HTML{Applet,Embed,Object}Elements
  635. // and RegExps. We would like to return object for those and we can
  636. // detect an invalid function by making sure that the function
  637. // object has a call method.
  638. return 'object';
  639. }
  640. return s;
  641. };
  642. /**
  643. * Returns true if the specified value is not |undefined|.
  644. * WARNING: Do not use this to test if an object has a property. Use the in
  645. * operator instead. Additionally, this function assumes that the global
  646. * undefined variable has not been redefined.
  647. * @param {*} val Variable to test.
  648. * @return {boolean} Whether variable is defined.
  649. */
  650. goog.isDef = function(val) {
  651. return val !== undefined;
  652. };
  653. /**
  654. * Returns true if the specified value is |null|
  655. * @param {*} val Variable to test.
  656. * @return {boolean} Whether variable is null.
  657. */
  658. goog.isNull = function(val) {
  659. return val === null;
  660. };
  661. /**
  662. * Returns true if the specified value is defined and not null
  663. * @param {*} val Variable to test.
  664. * @return {boolean} Whether variable is defined and not null.
  665. */
  666. goog.isDefAndNotNull = function(val) {
  667. // Note that undefined == null.
  668. return val != null;
  669. };
  670. /**
  671. * Returns true if the specified value is an array
  672. * @param {*} val Variable to test.
  673. * @return {boolean} Whether variable is an array.
  674. */
  675. goog.isArray = function(val) {
  676. return goog.typeOf(val) == 'array';
  677. };
  678. /**
  679. * Returns true if the object looks like an array. To qualify as array like
  680. * the value needs to be either a NodeList or an object with a Number length
  681. * property.
  682. * @param {*} val Variable to test.
  683. * @return {boolean} Whether variable is an array.
  684. */
  685. goog.isArrayLike = function(val) {
  686. var type = goog.typeOf(val);
  687. return type == 'array' || type == 'object' && typeof val.length == 'number';
  688. };
  689. /**
  690. * Returns true if the object looks like a Date. To qualify as Date-like
  691. * the value needs to be an object and have a getFullYear() function.
  692. * @param {*} val Variable to test.
  693. * @return {boolean} Whether variable is a like a Date.
  694. */
  695. goog.isDateLike = function(val) {
  696. return goog.isObject(val) && typeof val.getFullYear == 'function';
  697. };
  698. /**
  699. * Returns true if the specified value is a string
  700. * @param {*} val Variable to test.
  701. * @return {boolean} Whether variable is a string.
  702. */
  703. goog.isString = function(val) {
  704. return typeof val == 'string';
  705. };
  706. /**
  707. * Returns true if the specified value is a boolean
  708. * @param {*} val Variable to test.
  709. * @return {boolean} Whether variable is boolean.
  710. */
  711. goog.isBoolean = function(val) {
  712. return typeof val == 'boolean';
  713. };
  714. /**
  715. * Returns true if the specified value is a number
  716. * @param {*} val Variable to test.
  717. * @return {boolean} Whether variable is a number.
  718. */
  719. goog.isNumber = function(val) {
  720. return typeof val == 'number';
  721. };
  722. /**
  723. * Returns true if the specified value is a function
  724. * @param {*} val Variable to test.
  725. * @return {boolean} Whether variable is a function.
  726. */
  727. goog.isFunction = function(val) {
  728. return goog.typeOf(val) == 'function';
  729. };
  730. /**
  731. * Returns true if the specified value is an object. This includes arrays
  732. * and functions.
  733. * @param {*} val Variable to test.
  734. * @return {boolean} Whether variable is an object.
  735. */
  736. goog.isObject = function(val) {
  737. var type = typeof val;
  738. return type == 'object' && val != null || type == 'function';
  739. // return Object(val) === val also works, but is slower, especially if val is
  740. // not an object.
  741. };
  742. /**
  743. * Gets a unique ID for an object. This mutates the object so that further
  744. * calls with the same object as a parameter returns the same value. The unique
  745. * ID is guaranteed to be unique across the current session amongst objects that
  746. * are passed into {@code getUid}. There is no guarantee that the ID is unique
  747. * or consistent across sessions. It is unsafe to generate unique ID for
  748. * function prototypes.
  749. *
  750. * @param {Object} obj The object to get the unique ID for.
  751. * @return {number} The unique ID for the object.
  752. */
  753. goog.getUid = function(obj) {
  754. // TODO(arv): Make the type stricter, do not accept null.
  755. // In Opera window.hasOwnProperty exists but always returns false so we avoid
  756. // using it. As a consequence the unique ID generated for BaseClass.prototype
  757. // and SubClass.prototype will be the same.
  758. return obj[goog.UID_PROPERTY_] ||
  759. (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
  760. };
  761. /**
  762. * Removes the unique ID from an object. This is useful if the object was
  763. * previously mutated using {@code goog.getUid} in which case the mutation is
  764. * undone.
  765. * @param {Object} obj The object to remove the unique ID field from.
  766. */
  767. goog.removeUid = function(obj) {
  768. // TODO(arv): Make the type stricter, do not accept null.
  769. // DOM nodes in IE are not instance of Object and throws exception
  770. // for delete. Instead we try to use removeAttribute
  771. if ('removeAttribute' in obj) {
  772. obj.removeAttribute(goog.UID_PROPERTY_);
  773. }
  774. /** @preserveTry */
  775. try {
  776. delete obj[goog.UID_PROPERTY_];
  777. } catch (ex) {
  778. }
  779. };
  780. /**
  781. * Name for unique ID property. Initialized in a way to help avoid collisions
  782. * with other closure javascript on the same page.
  783. * @type {string}
  784. * @private
  785. */
  786. goog.UID_PROPERTY_ = 'closure_uid_' +
  787. Math.floor(Math.random() * 2147483648).toString(36);
  788. /**
  789. * Counter for UID.
  790. * @type {number}
  791. * @private
  792. */
  793. goog.uidCounter_ = 0;
  794. /**
  795. * Adds a hash code field to an object. The hash code is unique for the
  796. * given object.
  797. * @param {Object} obj The object to get the hash code for.
  798. * @return {number} The hash code for the object.
  799. * @deprecated Use goog.getUid instead.
  800. */
  801. goog.getHashCode = goog.getUid;
  802. /**
  803. * Removes the hash code field from an object.
  804. * @param {Object} obj The object to remove the field from.
  805. * @deprecated Use goog.removeUid instead.
  806. */
  807. goog.removeHashCode = goog.removeUid;
  808. /**
  809. * Clones a value. The input may be an Object, Array, or basic type. Objects and
  810. * arrays will be cloned recursively.
  811. *
  812. * WARNINGS:
  813. * <code>goog.cloneObject</code> does not detect reference loops. Objects that
  814. * refer to themselves will cause infinite recursion.
  815. *
  816. * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
  817. * UIDs created by <code>getUid</code> into cloned results.
  818. *
  819. * @param {*} obj The value to clone.
  820. * @return {*} A clone of the input value.
  821. * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
  822. */
  823. goog.cloneObject = function(obj) {
  824. var type = goog.typeOf(obj);
  825. if (type == 'object' || type == 'array') {
  826. if (obj.clone) {
  827. return obj.clone();
  828. }
  829. var clone = type == 'array' ? [] : {};
  830. for (var key in obj) {
  831. clone[key] = goog.cloneObject(obj[key]);
  832. }
  833. return clone;
  834. }
  835. return obj;
  836. };
  837. /**
  838. * Forward declaration for the clone method. This is necessary until the
  839. * compiler can better support duck-typing constructs as used in
  840. * goog.cloneObject.
  841. *
  842. * TODO(brenneman): Remove once the JSCompiler can infer that the check for
  843. * proto.clone is safe in goog.cloneObject.
  844. *
  845. * @type {Function}
  846. */
  847. Object.prototype.clone;
  848. /**
  849. * A native 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. * @suppress {deprecated} The compiler thinks that Function.prototype.bind
  859. * is deprecated because some people have declared a pure-JS version.
  860. * Only the pure-JS version is truly deprecated.
  861. */
  862. goog.bindNative_ = function(fn, selfObj, var_args) {
  863. return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
  864. };
  865. /**
  866. * A pure-JS implementation of goog.bind.
  867. * @param {Function} fn A function to partially apply.
  868. * @param {Object|undefined} selfObj Specifies the object which |this| should
  869. * point to when the function is run.
  870. * @param {...*} var_args Additional arguments that are partially
  871. * applied to the function.
  872. * @return {!Function} A partially-applied form of the function bind() was
  873. * invoked as a method of.
  874. * @private
  875. */
  876. goog.bindJs_ = function(fn, selfObj, var_args) {
  877. if (!fn) {
  878. throw new Error();
  879. }
  880. if (arguments.length > 2) {
  881. var boundArgs = Array.prototype.slice.call(arguments, 2);
  882. return function() {
  883. // Prepend the bound arguments to the current arguments.
  884. var newArgs = Array.prototype.slice.call(arguments);
  885. Array.prototype.unshift.apply(newArgs, boundArgs);
  886. return fn.apply(selfObj, newArgs);
  887. };
  888. } else {
  889. return function() {
  890. return fn.apply(selfObj, arguments);
  891. };
  892. }
  893. };
  894. /**
  895. * Partially applies this function to a particular 'this object' and zero or
  896. * more arguments. The result is a new function with some arguments of the first
  897. * function pre-filled and the value of |this| 'pre-specified'.<br><br>
  898. *
  899. * Remaining arguments specified at call-time are appended to the pre-
  900. * specified ones.<br><br>
  901. *
  902. * Also see: {@link #partial}.<br><br>
  903. *
  904. * Usage:
  905. * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');
  906. * barMethBound('arg3', 'arg4');</pre>
  907. *
  908. * @param {Function} fn A function to partially apply.
  909. * @param {Object|undefined} selfObj Specifies the object which |this| should
  910. * point to when the function is run.
  911. * @param {...*} var_args Additional arguments that are partially
  912. * applied to the function.
  913. * @return {!Function} A partially-applied form of the function bind() was
  914. * invoked as a method of.
  915. * @suppress {deprecated} See above.
  916. */
  917. goog.bind = function(fn, selfObj, var_args) {
  918. // TODO(nicksantos): narrow the type signature.
  919. if (Function.prototype.bind &&
  920. // NOTE(nicksantos): Somebody pulled base.js into the default
  921. // Chrome extension environment. This means that for Chrome extensions,
  922. // they get the implementation of Function.prototype.bind that
  923. // calls goog.bind instead of the native one. Even worse, we don't want
  924. // to introduce a circular dependency between goog.bind and
  925. // Function.prototype.bind, so we have to hack this to make sure it
  926. // works correctly.
  927. Function.prototype.bind.toString().indexOf('native code') != -1) {
  928. goog.bind = goog.bindNative_;
  929. } else {
  930. goog.bind = goog.bindJs_;
  931. }
  932. return goog.bind.apply(null, arguments);
  933. };
  934. /**
  935. * Like bind(), except that a 'this object' is not required. Useful when the
  936. * target function is already bound.
  937. *
  938. * Usage:
  939. * var g = partial(f, arg1, arg2);
  940. * g(arg3, arg4);
  941. *
  942. * @param {Function} fn A function to partially apply.
  943. * @param {...*} var_args Additional arguments that are partially
  944. * applied to fn.
  945. * @return {!Function} A partially-applied form of the function bind() was
  946. * invoked as a method of.
  947. */
  948. goog.partial = function(fn, var_args) {
  949. var args = Array.prototype.slice.call(arguments, 1);
  950. return function() {
  951. // Prepend the bound arguments to the current arguments.
  952. var newArgs = Array.prototype.slice.call(arguments);
  953. newArgs.unshift.apply(newArgs, args);
  954. return fn.apply(this, newArgs);
  955. };
  956. };
  957. /**
  958. * Copies all the members of a source object to a target object. This method
  959. * does not work on all browsers for all objects that contain keys such as
  960. * toString or hasOwnProperty. Use goog.object.extend for this purpose.
  961. * @param {Object} target Target.
  962. * @param {Object} source Source.
  963. */
  964. goog.mixin = function(target, source) {
  965. for (var x in source) {
  966. target[x] = source[x];
  967. }
  968. // For IE7 or lower, the for-in-loop does not contain any properties that are
  969. // not enumerable on the prototype object (for example, isPrototypeOf from
  970. // Object.prototype) but also it will not include 'replace' on objects that
  971. // extend String and change 'replace' (not that it is common for anyone to
  972. // extend anything except Object).
  973. };
  974. /**
  975. * @return {number} An integer value representing the number of milliseconds
  976. * between midnight, January 1, 1970 and the current time.
  977. */
  978. goog.now = Date.now || (function() {
  979. // Unary plus operator converts its operand to a number which in the case of
  980. // a date is done by calling getTime().
  981. return +new Date();
  982. });
  983. /**
  984. * Evals javascript in the global scope. In IE this uses execScript, other
  985. * browsers use goog.global.eval. If goog.global.eval does not evaluate in the
  986. * global scope (for example, in Safari), appends a script tag instead.
  987. * Throws an exception if neither execScript or eval is defined.
  988. * @param {string} script JavaScript string.
  989. */
  990. goog.globalEval = function(script) {
  991. if (goog.global.execScript) {
  992. goog.global.execScript(script, 'JavaScript');
  993. } else if (goog.global.eval) {
  994. // Test to see if eval works
  995. if (goog.evalWorksForGlobals_ == null) {
  996. goog.global.eval('var _et_ = 1;');
  997. if (typeof goog.global['_et_'] != 'undefined') {
  998. delete goog.global['_et_'];
  999. goog.evalWorksForGlobals_ = true;
  1000. } else {
  1001. goog.evalWorksForGlobals_ = false;
  1002. }
  1003. }
  1004. if (goog.evalWorksForGlobals_) {
  1005. goog.global.eval(script);
  1006. } else {
  1007. var doc = goog.global.document;
  1008. var scriptElt = doc.createElement('script');
  1009. scriptElt.type = 'text/javascript';
  1010. scriptElt.defer = false;
  1011. // Note(user): can't use .innerHTML since "t('<test>')" will fail and
  1012. // .text doesn't work in Safari 2. Therefore we append a text node.
  1013. scriptElt.appendChild(doc.createTextNode(script));
  1014. doc.body.appendChild(scriptElt);
  1015. doc.body.removeChild(scriptElt);
  1016. }
  1017. } else {
  1018. throw Error('goog.globalEval not available');
  1019. }
  1020. };
  1021. /**
  1022. * Indicates whether or not we can call 'eval' directly to eval code in the
  1023. * global scope. Set to a Boolean by the first call to goog.globalEval (which
  1024. * empirically tests whether eval works for globals). @see goog.globalEval
  1025. * @type {?boolean}
  1026. * @private
  1027. */
  1028. goog.evalWorksForGlobals_ = null;
  1029. /**
  1030. * Optional map of CSS class names to obfuscated names used with
  1031. * goog.getCssName().
  1032. * @type {Object|undefined}
  1033. * @private
  1034. * @see goog.setCssNameMapping
  1035. */
  1036. goog.cssNameMapping_;
  1037. /**
  1038. * Optional obfuscation style for CSS class names. Should be set to either
  1039. * 'BY_WHOLE' or 'BY_PART' if defined.
  1040. * @type {string|undefined}
  1041. * @private
  1042. * @see goog.setCssNameMapping
  1043. */
  1044. goog.cssNameMappingStyle_;
  1045. /**
  1046. * Handles strings that are intended to be used as CSS class names.
  1047. *
  1048. * This function works in tandem with @see goog.setCssNameMapping.
  1049. *
  1050. * Without any mapping set, the arguments are simple joined with a
  1051. * hyphen and passed through unaltered.
  1052. *
  1053. * When there is a mapping, there are two possible styles in which
  1054. * these mappings are used. In the BY_PART style, each part (i.e. in
  1055. * between hyphens) of the passed in css name is rewritten according
  1056. * to the map. In the BY_WHOLE style, the full css name is looked up in
  1057. * the map directly. If a rewrite is not specified by the map, the
  1058. * compiler will output a warning.
  1059. *
  1060. * When the mapping is passed to the compiler, it will replace calls
  1061. * to goog.getCssName with the strings from the mapping, e.g.
  1062. * var x = goog.getCssName('foo');
  1063. * var y = goog.getCssName(this.baseClass, 'active');
  1064. * becomes:
  1065. * var x= 'foo';
  1066. * var y = this.baseClass + '-active';
  1067. *
  1068. * If one argument is passed it will be processed, if two are passed
  1069. * only the modifier will be processed, as it is assumed the first
  1070. * argument was generated as a result of calling goog.getCssName.
  1071. *
  1072. * @param {string} className The class name.
  1073. * @param {string=} opt_modifier A modifier to be appended to the class name.
  1074. * @return {string} The class name or the concatenation of the class name and
  1075. * the modifier.
  1076. */
  1077. goog.getCssName = function(className, opt_modifier) {
  1078. var getMapping = function(cssName) {
  1079. return goog.cssNameMapping_[cssName] || cssName;
  1080. };
  1081. var renameByParts = function(cssName) {
  1082. // Remap all the parts individually.
  1083. var parts = cssName.split('-');
  1084. var mapped = [];
  1085. for (var i = 0; i < parts.length; i++) {
  1086. mapped.push(getMapping(parts[i]));
  1087. }
  1088. return mapped.join('-');
  1089. };
  1090. var rename;
  1091. if (goog.cssNameMapping_) {
  1092. rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ?
  1093. getMapping : renameByParts;
  1094. } else {
  1095. rename = function(a) {
  1096. return a;
  1097. };
  1098. }
  1099. if (opt_modifier) {
  1100. return className + '-' + rename(opt_modifier);
  1101. } else {
  1102. return rename(className);
  1103. }
  1104. };
  1105. /**
  1106. * Sets the map to check when returning a value from goog.getCssName(). Example:
  1107. * <pre>
  1108. * goog.setCssNameMapping({
  1109. * "goog": "a",
  1110. * "disabled": "b",
  1111. * });
  1112. *
  1113. * var x = goog.getCssName('goog');
  1114. * // The following evaluates to: "a a-b".
  1115. * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')
  1116. * </pre>
  1117. * When declared as a map of string literals to string literals, the JSCompiler
  1118. * will replace all calls to goog.getCssName() using the supplied map if the
  1119. * --closure_pass flag is set.
  1120. *
  1121. * @param {!Object} mapping A map of strings to strings where keys are possible
  1122. * arguments to goog.getCssName() and values are the corresponding values
  1123. * that should be returned.
  1124. * @param {string=} opt_style The style of css name mapping. There are two valid
  1125. * options: 'BY_PART', and 'BY_WHOLE'.
  1126. * @see goog.getCssName for a description.
  1127. */
  1128. goog.setCssNameMapping = function(mapping, opt_style) {
  1129. goog.cssNameMapping_ = mapping;
  1130. goog.cssNameMappingStyle_ = opt_style;
  1131. };
  1132. /**
  1133. * To use CSS renaming in compiled mode, one of the input files should have a
  1134. * call to goog.setCssNameMapping() with an object literal that the JSCompiler
  1135. * can extract and use to replace all calls to goog.getCssName(). In uncompiled
  1136. * mode, JavaScript code should be loaded before this base.js file that declares
  1137. * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is
  1138. * to ensure that the mapping is loaded before any calls to goog.getCssName()
  1139. * are made in uncompiled mode.
  1140. *
  1141. * A hook for overriding the CSS name mapping.
  1142. * @type {Object|undefined}
  1143. */
  1144. goog.global.CLOSURE_CSS_NAME_MAPPING;
  1145. if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {
  1146. // This does not call goog.setCssNameMapping() because the JSCompiler
  1147. // requires that goog.setCssNameMapping() be called with an object literal.
  1148. goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;
  1149. }
  1150. /**
  1151. * Abstract implementation of goog.getMsg for use with localized messages.
  1152. * @param {string} str Translatable string, places holders in the form {$foo}.
  1153. * @param {Object=} opt_values Map of place holder name to value.
  1154. * @return {string} message with placeholders filled.
  1155. */
  1156. goog.getMsg = function(str, opt_values) {
  1157. var values = opt_values || {};
  1158. for (var key in values) {
  1159. var value = ('' + values[key]).replace(/\$/g, '$$$$');
  1160. str = str.replace(new RegExp('\\{\\$' + key + '\\}', 'gi'), value);
  1161. }
  1162. return str;
  1163. };
  1164. /**
  1165. * Exposes an unobfuscated global namespace path for the given object.
  1166. * Note that fields of the exported object *will* be obfuscated,
  1167. * unless they are exported in turn via this function or
  1168. * goog.exportProperty
  1169. *
  1170. * <p>Also handy for making public items that are defined in anonymous
  1171. * closures.
  1172. *
  1173. * ex. goog.exportSymbol('Foo', Foo);
  1174. *
  1175. * ex. goog.exportSymbol('public.path.Foo.staticFunction',
  1176. * Foo.staticFunction);
  1177. * public.path.Foo.staticFunction();
  1178. *
  1179. * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',
  1180. * Foo.prototype.myMethod);
  1181. * new public.path.Foo().myMethod();
  1182. *
  1183. * @param {string} publicPath Unobfuscated name to export.
  1184. * @param {*} object Object the name should point to.
  1185. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  1186. * is |goog.global|.
  1187. */
  1188. goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {
  1189. goog.exportPath_(publicPath, object, opt_objectToExportTo);
  1190. };
  1191. /**
  1192. * Exports a property unobfuscated into the object's namespace.
  1193. * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);
  1194. * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);
  1195. * @param {Object} object Object whose static property is being exported.
  1196. * @param {string} publicName Unobfuscated name to export.
  1197. * @param {*} symbol Object the name should point to.
  1198. */
  1199. goog.exportProperty = function(object, publicName, symbol) {
  1200. object[publicName] = symbol;
  1201. };
  1202. /**
  1203. * Inherit the prototype methods from one constructor into another.
  1204. *
  1205. * Usage:
  1206. * <pre>
  1207. * function ParentClass(a, b) { }
  1208. * ParentClass.prototype.foo = function(a) { }
  1209. *
  1210. * function ChildClass(a, b, c) {
  1211. * goog.base(this, a, b);
  1212. * }
  1213. * goog.inherits(ChildClass, ParentClass);
  1214. *
  1215. * var child = new ChildClass('a', 'b', 'see');
  1216. * child.foo(); // works
  1217. * </pre>
  1218. *
  1219. * In addition, a superclass' implementation of a method can be invoked
  1220. * as follows:
  1221. *
  1222. * <pre>
  1223. * ChildClass.prototype.foo = function(a) {
  1224. * ChildClass.superClass_.foo.call(this, a);
  1225. * // other code
  1226. * };
  1227. * </pre>
  1228. *
  1229. * @param {Function} childCtor Child class.
  1230. * @param {Function} parentCtor Parent class.
  1231. */
  1232. goog.inherits = function(childCtor, parentCtor) {
  1233. /** @constructor */
  1234. function tempCtor() {};
  1235. tempCtor.prototype = parentCtor.prototype;
  1236. childCtor.superClass_ = parentCtor.prototype;
  1237. childCtor.prototype = new tempCtor();
  1238. childCtor.prototype.constructor = childCtor;
  1239. };
  1240. /**
  1241. * Call up to the superclass.
  1242. *
  1243. * If this is called from a constructor, then this calls the superclass
  1244. * contructor with arguments 1-N.
  1245. *
  1246. * If this is called from a prototype method, then you must pass
  1247. * the name of the method as the second argument to this function. If
  1248. * you do not, you will get a runtime error. This calls the superclass'
  1249. * method with arguments 2-N.
  1250. *
  1251. * This function only works if you use goog.inherits to express
  1252. * inheritance relationships between your classes.
  1253. *
  1254. * This function is a compiler primitive. At compile-time, the
  1255. * compiler will do macro expansion to remove a lot of
  1256. * the extra overhead that this function introduces. The compiler
  1257. * will also enforce a lot of the assumptions that this function
  1258. * makes, and treat it as a compiler error if you break them.
  1259. *
  1260. * @param {!Object} me Should always be "this".
  1261. * @param {*=} opt_methodName The method name if calling a super method.
  1262. * @param {...*} var_args The rest of the arguments.
  1263. * @return {*} The return value of the superclass method.
  1264. */
  1265. goog.base = function(me, opt_methodName, var_args) {
  1266. var caller = arguments.callee.caller;
  1267. if (caller.superClass_) {
  1268. // This is a constructor. Call the superclass constructor.
  1269. return caller.superClass_.constructor.apply(
  1270. me, Array.prototype.slice.call(arguments, 1));
  1271. }
  1272. var args = Array.prototype.slice.call(arguments, 2);
  1273. var foundCaller = false;
  1274. for (var ctor = me.constructor;
  1275. ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
  1276. if (ctor.prototype[opt_methodName] === caller) {
  1277. foundCaller = true;
  1278. } else if (foundCaller) {
  1279. return ctor.prototype[opt_methodName].apply(me, args);
  1280. }
  1281. }
  1282. // If we did not find the caller in the prototype chain,
  1283. // then one of two things happened:
  1284. // 1) The caller is an instance method.
  1285. // 2) This method was not called by the right caller.
  1286. if (me[opt_methodName] === caller) {
  1287. return me.constructor.prototype[opt_methodName].apply(me, args);
  1288. } else {
  1289. throw Error(
  1290. 'goog.base called from a method of one name ' +
  1291. 'to a method of a different name');
  1292. }
  1293. };
  1294. /**
  1295. * Allow for aliasing within scope functions. This function exists for
  1296. * uncompiled code - in compiled code the calls will be inlined and the
  1297. * aliases applied. In uncompiled code the function is simply run since the
  1298. * aliases as written are valid JavaScript.
  1299. * @param {function()} fn Function to call. This function can contain aliases
  1300. * to namespaces (e.g. "var dom = goog.dom") or classes
  1301. * (e.g. "var Timer = goog.Timer").
  1302. */
  1303. goog.scope = function(fn) {
  1304. fn.call(goog.global);
  1305. };