Skip to content

How to migrate from goog.base

John Lenz edited this page May 17, 2016 · 1 revision

How to migrate from goog.base

goog.base is not compatible with ES6/ES5 Strict mode. While the Closure Compiler rewrites goog.base in a way that is strict mode compatible, goog.base can not be used uncompiled in strict code.

The goog.base Alternative

To provide an alternative to goog.base, a static base method is added to a class constructor by goog.inherits. This method, while similar to goog.base, is used differently from a constructor. Here is an example, with goog.base:

/** @constructor @extends {MySuperClass} */
function MyClass(a, b) {
  goog.base(this, a, b);
}
goog.inherits(MyClass, MySuperClass);
MyClass.prototype.method = function() {
  goog.base(this, 'method');
};

with the class specific base method

/** @constructor @extends {MySuperClass} */
function MyClass(a, b) {
  MyClass.base(this, 'constructor', a, b);
}
goog.inherits(MyClass, MySuperClass);
MyClass.prototype.method = function() {
  MyClass.base(this, 'method');
};

Prevent regressions

You can also enable the useOfGoogBase (USE_OF_GOOG_BASE from the Java API) diagnostic group in your Closure Compiler options to avoid regressions. To emit an error when goog.base is used add --jscomp_error=useOfGoogBase to the compiler flags or equivalent.

Known Issues

Mocking classes

There is one major difference between goog.base and the base method added to the constructor. goog.base performed a dynamic lookup of the associated prototype chain while the base method uses a static reference to a known name (the class name). Certain mocking patterns rely on overwriting the class with a subtype of the class create with goog.inherits:

var MyMock = function() {};
goog.inherits(MyMock, MockedClass);
MockedClass = MyMock;

This will create an infinite loop when a method using the base method in the original class calls the MyMock.base (renamed MockedClass.base) which result in a call to itself. The work-around is to (1) avoid using the base method in mocks and (2) to preserve the original base method.

var mockedClassBase = MockedClass.base;
var MyMock = function() {};
goog.inherits(MyMock, MockedClass);
MockedClass = MyMock;
MockedClass.base = mockedClassBase;