Skip to content

Instantly share code, notes, and snippets.

@zachshallbetter
Forked from PatrickJS/factory-shared.es5.js
Last active April 24, 2019 03:37
Show Gist options
  • Save zachshallbetter/28b4e9f473b0bfabb4cd to your computer and use it in GitHub Desktop.
Save zachshallbetter/28b4e9f473b0bfabb4cd to your computer and use it in GitHub Desktop.
Examples of OOP "class" with "inheritance" done using JavaScript including languages that transpile into js. Take notice to the amount of boilerplate that's needed in ES5 compared to ES6. These examples all have the same interface with pros/cons for each pattern. If they seem similar that's whole point especially the difference between prototypa…
var EventEmitter = require('events').EventEmitter;
var _ = require('lodash');
// Factory shared
var makePerson = function() {
var person = {};
EventEmitter.call(person);
person.wallet = 0;
_.extend(person, personMethods)
return person;
}
var personMethods = {};
_.extend(personMethods, EventEmitter.prototype)
personMethods.talk = function() {
};
var person = makePerson();
person.talk();
var EventEmitter = require('events').EventEmitter;
// Prototypal
function Person() {
var person = Object.create(Person.prototype);
EventEmitter.call(person);
person.wallet = 0;
return person;
}
Person.prototype = Object.create(EventEmitter.prototype);
Person.prototype.talk = function() {
};
var person = Person();
person.talk();
import { EventEmitter } from 'events';
// AtScript pseudo-classical
class Person extends EventEmitter {
wallet;
constructor() {
super();
this.wallet = 0;
}
talk() {
}
}
var person = new Person();
person.talk();
{EventEmitter} = require 'events'
# Coffeescript pseudo-classical
class Person extends EventEmitter
constructor: ->
super()
@wallet = 0
talk: ->
person = new Person()
person.talk()
import 'package:event_emitter/event_emitter.dart';
/// Dart pseudo-classical
class Person extends EventEmitter {
num wallet;
Person() {
this.wallet = 0;
}
void talk() {
}
}
var person = new Person();
person.talk();
var EventEmitter = require('events').EventEmitter;
// ES5 Pseudo-classical
function Person() {
EventEmitter.call(this);
this.wallet = 0;
}
Person.prototype = Object.create(EventEmitter.prototype);
Person.constructor = Person;
Person.prototype.talk = function() {
};
var person = new Person();
person.talk();
import { EventEmitter } from 'events';
// ES6 pseudo-classical
class Person extends EventEmitter {
constructor() {
super();
this.wallet = 0;
}
talk() {
}
}
let person = new Person();
person.talk();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment