Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Prototypical inheritance in ECMAScript 6

Prototypical inheritance in ECMAScript 6

An overview of new ECMAScript 6 features related to the prototypical inheritance model: __proto__ updates, super references, real methods and more.

Jev Zelenkov

June 18, 2015
Tweet

More Decks by Jev Zelenkov

Other Decks in Technology

Transcript

  1. function Criminal () { console.log("new crime suspect is in town.");

    } Criminal.prototype.murder = function(person) { console.log(`Killing ${person} softly.`); } var lee_oswald = new Criminal(); // (A) lee_oswald.murder("John F. Kennedy"); construct & new
  2. function newCriminal () { var _this = {}; // a

    new object is created. Used as `this` in the function context _this.__proto__ = Criminal.prototype; // a special __proto__ property is set Criminal.call(_this); return _this; // newly created object is returned } var some_dude = newCriminal(); some_dude.murder("George Woosh"); fake new function newCriminal () { var _this = {}; // (A) _this.__proto__ = Criminal.prototype; // (B) Criminal.call(_this); return _this; // (C) } var some_dude = newCriminal(); some_dude.murder("George Woosh");
  3. function President () { } President.prototype.speak = function () {

    console.log("Yes, we can!”); }; var lee_oswald = new Criminal(); Object.setPrototypeOf(lee_oswald, President.prototype); lee_oswald.__proto__ = President.prototype; lee_oswald.speak(); // OK, this is awkward __pr0to!
  4. var thief = { __proto__: Criminal.prototype, bully(name) { // (A)

    super.bully(name); console.log(“steal their food!!!”); } } stealing…
  5. // ES 5 crime = { victim: victim, location: location,

    commit: function () { // ... } } props / meh!dots // ES 6 crime = { victim, location, commit () { // ... } }
  6. class Criminal { constructor(name) { this.name = name; } sayName()

    { // ... } } clazz function Criminal (name) { this.name = name; } Criminal.prototype.sayName(){ // ... }
  7. static methods class Criminal { constructor(name) { this.name = name;

    } static isCriminal() { // ... } } function Criminal { this.name = name; } Criminal.isCriminal = fun() { // ... }
  8. class Criminal { murder() {} }
 class Politician extends Criminal

    { fundraise() {} } Politician.prototype.__proto__ === Criminal.prototype wires __proto__ ref
  9. thanks! @jevzee this presentation: https://speakerdeck.com/jevzee read more: • Understanding ES6 — Nicholas

    Zakas • You don’t know JS / ES6 & Beyond — Kyle Simpson (Getify) • Exploring ES6 — Axel Rauschmayer • JavaScript Allongé, the “Six” Edition — Reg Braithwaite