Return to Snippet

Revision: 28428
at July 8, 2010 05:42 by hedgerwang


Initial Code
/**
 * Extends a sub class from a super class.
 * @param {Function} subClass The subclass.
 * @param {Function} superClass The super class to extend. 
 */
function extends(subClass, superClass) {
  var midClass = function() {
  };
  midClass.prototype = superClass.prototype;
  subClass.prototype = new midClass();
  subClass.superClass = superClass;
}

/**
 * A person.
 * @constructor
 * @param {string} name
 */
function Person(name) {
  /**
   * @private {string}
   */
  this._name = name;
}


/**
 * @return {string}
 */
Person.prototype.getName = function() {
  return this._name;
};

/**
 * A user.
 * @constructor
 * @inheritDoc
 * @extends {Person}
 */
function User(name) {
  User.superClass.call(this, name);
}
extends(User, Person);


/**
 * @return {number}
 */
User.prototype.getNameLength = function() {
  return this.getName().length;
};

// Demo
var user = new User('John Doe');
user.alertName(); // John Doe
document.writeln(user.getName()); // John Doe
document.writeln(user instanceof User); // true;
document.writeln(user instanceof Person); // true;

Initial URL


Initial Description


Initial Title
Classic Class Prototype  Inheritance

Initial Tags
javascript

Initial Language
JavaScript