Skip to content

Instantly share code, notes, and snippets.

@tobynet tobynet/index.html
Last active Sep 7, 2017

Embed
What would you like to do?
[WIP] inheritance.in.js
<p>Open the <em>Console</em> and see it!</p>
<img src="https://i.gyazo.com/e3ac4649fb1d6e1f93a47ef5a8dd9c9e.gif" style="border: 1px solid lightgray;">
<p>or press <code>F12</code> to open console in DevTools on your browser.</p>
// Define System.Out.Println() for debugging
const System = { Out: { Println: function(target, f, name) {
const old = target.ver;
f.call(target);
console.log(`${target.constructor.name}\t ver ${old} -> ${target.ver} (After ${name})`);
}}}
// Define class(ES5)
// * Ref: https://developer.mozilla.org/ja/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
const Java = function() {
if (!(this instanceof Java)) { return new Java(); }
this.ver = 1;
}
Java.prototype.update = function() { this.ver++; }
const java = new Java();
System.Out.Println(java, java.update, 'update');
// Inheritance (ES5)
const NotJava = function() {
if (!(this instanceof NotJava)) { return new NotJava(); }
Java.call(this);
this.ver = 65536;
}
// 🤔 boring...
NotJava.prototype = Object.create(Java.prototype);
NotJava.prototype.constructor = NotJava;
NotJava.prototype.update = function() { this.ver = Math.pow(this.ver, 2); }
NotJava.prototype.downgrade = function() { this.ver = Math.floor(this.ver / 1024); }
const notJava = new NotJava();
System.Out.Println(notJava, notJava.update, 'update');
System.Out.Println(notJava, notJava.downgrade, 'downgrade');
// Define class(ES2015)
// * Ref: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes
class Scala {
constructor() {
this.ver = 100;
}
update() {
this.ver++;
}
}
const scala = new Scala();
System.Out.Println(scala, scala.update, 'update');
// Inheritance (ES2015)
class NotScala extends Scala {
constructor(...args) {
super(...args);
this.ver = 100000;
}
update() {
this.ver = Math.pow(this.ver, 2);
}
downgrade() {
this.ver = 0;
}
}
const notScala = new NotScala();
System.Out.Println(notScala, notScala.update, 'update');
System.Out.Println(notScala, notScala.downgrade, 'downgrade');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.