Frage

Update: I've updated the question to state that the code in question is for a subclass in Google Closure.

I'm looking through some JavaScript code that defines a subclass and saw that an object literal is being used to set the prototype. Note that this code is using Google Closure Library and will be compiled in advanced mode with Google Closure Compiler. (Not sure if this matters for this question.) The code looks like this:

company.app.MyClass = function(param) {
  this.field = 0;
};

company.app.MyClass.prototype = {
  function1: function() {
    //Do stuff.
  },
  function2: function() {
    //Do more stuff.
  };
};

company.app.MySubClass = function(param) {
  company.app.MyClass.call(this, param);
};

company.app.MySubClass.prototype = {
  function3: function() {
    //Do stuff.
  },
  function4: function() {
    //Do more stuff.
  };
};

goog.inherits(company.app.MySubClass, company.app.MyClass);

All of the samples I have seen for creating classes with Google Closure add fields and functions to the prototype instead of setting it to an entirely new object with an Object literal. So the code for MySubClass would look like this:

company.app.MySubClass.prototype.function3 = function() {
    //Do stuff.
};
company.app.MySubClass.prototype.function4 = function() {
    //Do more stuff.
};

I don't know exactly what is happening when goog.inherit is called, but I was wondering if setting the prototype of the sub class to a new object literal could cause problems with the inheritance of the base class, MyClass?

War es hilfreich?

Lösung

I don't know exactly what is happening when goog.inherit is called

Check the code of goog.inherits then. It should look familiar if you know the common Object.create shim and what it does.

As you can see, it completely overwrites the childCtor.prototype, not preserving any old properties on it - which can be problematic and indeed trahes the function3 and function4 methods you previously defined on it in your example. So you will need to inherit first, then extend the new prototype object.

If you still want to use an object literal, that is no problem:

company.app.MySubClass = function(param) {
  company.app.MyClass.call(this, param);
};
goog.inherits(company.app.MySubClass, company.app.MyClass);
goog.mixin(company.app.MySubClass.prototype, {
  function3: function() {
    //Do stuff.
  },
  function4: function() {
    //Do more stuff.
  }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top