Prototypal inheritance

by david_i_smith

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

JavaScript

// objects created with syntax constructs
(function() {
	var o = {a: 1};
  var a = ['yo', 'whadup', '?'];
  function f() {
  	return 2;
  };
}());

// objects created with a constructor
(function() {
	var Graph = function() {
  	this.vertices = [];
    this.edges = [];
  };
  Graph.prototype.addVertex = function(v) {
  	this.vertices.push(v);
  };
  var graph = new Graph();
  console.log(graph.hasOwnProperty('hasOwnProperty'));
  console.log(graph.hasOwnProperty('vertices'));
}());

// objects created with Object.create()
(function() {
	function A() {}
  A.prototype.foo = function() {
    console.log('foo');
  };
	function B() {}
  B.prototype = Object.create(A.prototype);
  B.prototype.bar = function() {
    console.log('bar');
  };
	function C() {}
  C.prototype = Object.create(A.prototype);
  C.prototype.baz = function() {
    console.log('baz');
  };
  var ab = new B();
  ab.foo();
  ab.bar();
  var ac = new C();
  ac.foo();
  ac.baz();
}());

// objects created with the class keyword
(function() {

  var Person = {
    numArms: 2,
    numLegs: 2
  };

  var Crawler = {
    crawl: function () {
      console.log('crawling');
    }
  };

  var Walker = {
    walk: function () {
      console.log('walking');
    }
  };

  var Runner = {
    run: function () {
      console.log('running');
    }
  };

  var Talker = {
    talk: function () {
      console.log('talking');
    }
  };

  var arthur = _.assign(_.create(Person), {
    name: 'Arthur',
    isDescendedFrom: function (proto) {
      console.log(Object.getPrototypeOf(this) === proto);
    }
  }, Crawler, Walker, Runner, Talker);
  //arthur.crawl();
  //arthur.walk();
  //arthur.run();
  //arthur.talk();
  //arthur.isDescendedFrom(Person);

}());