1

I am trying to annotate my javascript so that closure doesnt rename all the symbols since i am working with vanilla javascript as well.

/**
* @constructor
* @expose
* @type{foo}
*/

foo = function (el, args) {
"use strict";
var s = "Hello World";
/*
* @expose
* @this {foo}
* @type {function}
*/
this.introduce = function () {
    return s;
 };
};

However the generated output when i run it through the closure compiler with advanced optimization is

foo = function() {
 this.a = function() {
 return"Hello World"

} };

How do i ask closure to preserve the name introduce since this will be called from an external javascript.

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
Gokul
  • 237
  • 3
  • 13

1 Answers1

4

The following options may be used to prevent the Closure Compiler from renaming symbols:

If you do not want to define methods on the function prototype as shown in your example, then you could export the constructor foo with goog.exportSymbol and use @expose to export methods.

/**
 * @param {Element} el
 * @param {...*} args
 * @constructor
 */
var foo = function (el, args) {
  "use strict";

  /** @private */
  this.msg_ = "Hello World";

  /**
   * @this {foo}
   * @return {string}
   * @expose
   */
  this.introduce = function () {
    return this.msg_;
  };
};
goog.exportSymbol('foo', foo);

By defining methods on the function prototype, goog.exportSymbol can be used to export both the constructor as well as method names.

/**
 * @param {Element} el
 * @param {...*} args
 * @constructor
 */
var foo = function (el, args) {
  "use strict";

  /** @private */
  this.msg_ = 'Hello World!';
};
goog.exportSymbol('foo', foo);

/**
 * @return {string}
 */
foo.prototype.introduce = function () {
  return this.msg_;
};
goog.exportSymbol('foo.prototype.introduce', foo.prototype.introduce);

See these related stackoverflow questions:

Community
  • 1
  • 1
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
  • When i use the @expose annotation on the prototype methods,it works fine without having to use goog.exportSymbol. However the expose annotation doesnt seem to work on functions being added directly to the object rather than the prototype. I would like to use it in the former case so that i can use closures instead of trying to have member variables all over. – Gokul Jul 27 '12 at 06:40
  • Answer updated to explain @expose and provide working examples using methods defined directly on the constructor as well as the function prototype. – Christopher Peisert Jul 27 '12 at 17:27
  • Don't use @expose annotation. It's brittle. https://groups.google.com/forum/#!msg/closure-compiler-discuss/B_WpQgpaoKw/4GZyCCTL4nQJ – Daniel Steigerwald Aug 19 '14 at 20:47
  • 1
    `@expose` is now deprecated. It is replaced by `@nocollapse` and `@export`. The compiler will warn about any usage of `@expose`. – Chad Killingsworth Apr 17 '15 at 15:36