1. JavaScript: prototype property

    In JavaScript, prototype is a property of functions which easily allows for object extension and inheritance.

    var x = {};
    x.prototype; // undefined
    
    x = [];
    x.prototype; // undefined
    
    x = function(){};
    x.prototype; // Object
    

    To extend an object with prototype:

    Array.prototype.add = function() {
      var length = this.length;
      var sum = 0;
      for (var i = 0; i < length; i++) {
        if (!isNaN(this[i])) {
          sum += this[i];
        }
      }
      return sum;
    };
    
    [2, 3, 5, 'ha ha ha ha', 10].add(); //20
    

    The above serves as an example. Do not extend native objects lightly. This topic is discussed extensively at javascriptweblog.

    To inherit from an object with prototype:

    var Parent = function() {
      this.name = 'parent';
      this.getName = function() {
        return this.name;
      };
    };
    
    var Child = function() {
      this.name = 'child';
    };
    
    Child.prototype = new Parent();
    Child.prototype.constructor = Child;
    
    var p = new Parent();
    p.getName(); // 'parent'
    
    var c = new Child();
    c.getName(); // 'child'
    
    Child.prototype.actChildish = function() {
      // childish behavior
    };
    
    c.actChildish();
    
    p.actChildish(); // error
    

    Note that updating Child’s prototype to include actChildish updates the already instantiated object c and that p did not get actChildish added to its prototype.

Notes

  1. hoorayjavascript posted this