cklanac
4/29/2017 - 5:23 PM

Walking the __proto__chain

Walking the __proto__chain

javascript:void(!function(a){function c(a){if(a.__proto__){var f=e(a.__proto__),g=e(a.__proto__.__proto__);b.push("["+d(a)+"|"+f+"]-__proto__>"+(a.__proto__.__proto__?"["+d(a.__proto__)+"|"+g+"]":"[null]")),c(a.__proto__)}}function d(a){return a.__proto__.__proto__?a.__proto__.constructor.name:"Base"}function e(a){var b="";for(var c in a)a.hasOwnProperty(c)&&(b+=c,"function"==typeof a[c]&&(b+="()"),b+=";");return b}var a=prompt("Please enter the variable that points to the object.");window[a]||console.log("Sorry, that variable is not found.");var b=["["+a+"|"+e(window[a])+"]-__proto__>["+window[a].__proto__.constructor.name+"|"+e(window[a].__proto__)+"]"];c(window[a]);window.open("http://yuml.me/diagram/scruffy/class/"+b.join(","))}())
class Animal { 
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        console.log(this.name + ' makes a noise.');
    }
}

class Dog extends Animal {
    speak() {
        console.log(this.name + ' barks.');
    }
}

var d = new Dog('Mitzie');


function walkProtoChain(obj) {
    if (!obj) return 'Base';
    return `${obj.constructor.name} --> ${walkProtoChain(obj.__proto__)}`
}

var str = walkProtoChain(d);
console.log(str)
;(function(o) {
    var o = prompt("Please enter the variable that points to the object.");
    if (!window[o]) {
      console.log("Sorry, that variable is not found.")
    }
    var protoChain = ['[' + o + '|' + getProps(window[o]) + ']-__proto__>['+window[o].__proto__.constructor.name+'|'+getProps(window[o].__proto__)+']'];
    function buildChain(o) {
      if (!o.__proto__) return;
      var thisProps = getProps(o.__proto__);
      var parentProps = getProps(o.__proto__.__proto__);      
      protoChain.push('[' + getName(o) + '|' + thisProps + ']-__proto__>' + ((o.__proto__.__proto__) ? '[' + getName(o.__proto__) + '|' + parentProps + ']' : '[null]'));      
      buildChain(o.__proto__);
    }

    function getName(o){
      if (o.__proto__.__proto__) {
        return o.__proto__.constructor.name;
      } else {
        return 'Base';
      }
    }
    function getProps(o) {
      var props = '';
      for (var p in o) {
        if (o.hasOwnProperty(p)) {
          props += p;
          if (typeof o[p] === 'function') {
            props += '()';
          }
          props += ';';
        }
      }
      return props;
    }

    var str = buildChain(window[o]);
    window.open("http://yuml.me/diagram/scruffy/class/" + protoChain.join(','));
  }());