Skip to content

Instantly share code, notes, and snippets.

@twisterghost
Created August 15, 2017 14:14
Show Gist options
  • Save twisterghost/f49a029799d447e19410b42fd3b3eec8 to your computer and use it in GitHub Desktop.
Save twisterghost/f49a029799d447e19410b42fd3b3eec8 to your computer and use it in GitHub Desktop.
ES5 class extending
var assert = require('assert');
// Define parent "class"
var Parent = function Parent(name) {
this.name = name;
this.isYoung = false;
};
Parent.prototype.speak = function speak() {
console.log('Hello, my name is ' + this.name);
if (this.isYoung) {
console.log('I am young!');
} else {
console.log('I am not young.');
}
};
// Extend parent "class"
var Child = function Child(name) {
Parent.apply(this, arguments);
this.isYoung = true;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// Let's test it out
var lisa = new Parent('Lisa');
var abdul = new Child('Abdul');
lisa.speak();
abdul.speak();
// Assert type inherits
assert.equal(lisa instanceof Child, false);
assert.ok(lisa instanceof Parent);
assert.ok(abdul instanceof Child);
assert.ok(abdul instanceof Parent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment