Why is `goog.base (this)` necessary in addition to `goog.inherits ()`?

In this Google Closure javascript code snippet involving a constructor, why is goog.base(this);it necessary? Not Fooalready inherited from a single use with goog.inherits(foo, goog.Disposable);?

goog.provide('Foo');

/**
 * @constructor
 * @extends {goog.Disposable}
 */
Foo = function() {
  goog.base(this);
}     
goog.inherits(foo, goog.Disposable);

foo.prototype.doSomething = function(){
  ...
}

foo.prototype.disposeInternal = function(){
  ...
}
+5
source share
3 answers

goog.inherits (childConstructor, parentConstructor)

goog.inherits() sets the prototype chain from the child constructor to the parent constructor.

/**
 * Inherit the prototype methods from one constructor into another.
 * @param {Function} childCtor Child class.
 * @param {Function} parentCtor Parent class.
 */
goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  /** @override */
  childCtor.prototype.constructor = childCtor;
};


"" (.. , this). goog.inherits() , . , .

/**
 * @param {string} name The parent name.
 * @constructor
 */
var Parent = function(name) {
  /**
   * @type {string}
   * @private
   */
  this.name_ = name;
}

/**
 * @param {string} name The child name.
 * @constructor
 * @extends {Parent}
 */
var Child = function(name) {
  Parent.call(this, name);
}
goog.inherits(Child, Parent);


goog.base(self, opt_methodName, var_args)

goog.base() - , call() apply().

[goog.base()] , 1-N.

, . , . 2-N.

, goog.inherits .

Closure goog.base() .

/**
 * @param {string} name The child name.
 * @constructor
 * @extends {Parent}
 */
var Child = function(name) {
  goog.base(this, name);
}
goog.inherits(Child, Parent);


+9

JavaScript this , , , ( Java, # ++). , this goog.Disposable this , , .call .apply. , goog.Disposable(), this goog.

, this :

  • obj.func() obj["func"]() — , , . , this obj.

  • call apply, , this . call apply , : call , . foo.call(obj, 1, 2, 3) foo this, obj, 1, 2 3. apply : foo.apply(obj, [1, 2, 3]); ( [ ], var a = [1, 2, 3]; foo.call(obj, a);

:

+1

Foo = function() {
  goog.base(this); //call parent constructor
}     
goog.inherits(foo, goog.Disposable);

public class Foo extends Disposable(){
  public Foo(){
    super(); // call parent constructor
  }
}
+1

All Articles