What is the preferred way to define properties for Google Closure classes?

The following example shows a class that extends the goog.ui.Component component.

Should class properties be defined outside the constructor, as shown below, or should they be defined only inside the constructor?

Is it possible to initialize null properties?

goog.provide("org.something.SomeClass");

/**
 * @type {Object}
 * @private
 **/
org.something.SomeClass.prototype.anObject_ = null;

/**
 * @type {Element}
 * @private
 **/
org.something.SomeClass.prototype.anElement_ = null;

/**
 * @param {goog.dom.DomHelper=} opt_domHelper
 * @constructor
 * @extends {goog.ui.Component}
*/
org.something.SomeClass = function () {
    goog.ui.Component.call(this, opt_domHelper);

    this.anObject_ = {};
    this.anElement_ = new Element();
};
goog.inherits(org.something.SomeClass, goog.ui.Component);
+5
source share
2 answers

The Closure Library implements classes with properties defined both on the prototype and inside the constructor function. In addition to exploring the source code for the Closure library, we’ll look at some questions when deciding whether to define a property in a prototype or constructor.

?

, (, VIN ), , .

/**
 * A car.
 * @param {string} vin The Vehicle Identification Number.
 * @constructor
 */
Car = function(vin) {

  /**
   * The Vehicle Identification Number.
   * @type {string}
   * @private
   */
  this.vin_ = vin;
}; 

(, , , ) (, Object, Array)?

, . , , .

/**
 * The number of cylinders in the engine.
 * @type {number}
 * @private
 */
Car.prototype.cylinders_ = 4;

/**
 * Sets the number of cylinders in the engine.
 * @param {number} cylinders The number of cylinders.
 */
Car.prototype.setCylinders = function(cylinders) {
  if (this.cylinders_ == cylinders) {
    // Since the number of cylinders has not changed, do not add a new
    // instance property to shadow the prototype property. Instead, continue
    // to use the prototype property.
    return;
  }

  // Defines cylinders_ property on the instance object that shadows
  // Car.prototype.cylinders_
  this.cylinders_ = cylinders;
};

/**
 * Gets the number of cylinders in the engine.
 * @return {number} The number of cylinders.
 */
Car.prototype.getCylinders = function() {
  return this.cylinders_;
};

, .

var myCar = new Car("1HGCM82633A004352");
alert(myCar.getCylinders()); // Alerts 4.

myCar.setCylinders(6);
alert(myCar.getCylinders()); // Alerts 6;

// Delete the instance property and let the prototype property
// "shine through".
delete myCar.cylinders_;
alert(myCar.getCylinders()); // Alerts 4;


, Array Object, mutable . , , .

null?

Closure , null.. , , , 4, .

+3

, V8, . , V8 ( IO2012). , . , , .:-)

0

All Articles