Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Last active February 17, 2016 19:44
Show Gist options
  • Save rebolyte/38ad27817fa8d7cf3853 to your computer and use it in GitHub Desktop.
Save rebolyte/38ad27817fa8d7cf3853 to your computer and use it in GitHub Desktop.
Testing out the OLOO pattern
/* jshint esversion: 5, strict: global, devel: true */
// Requires an Object.assign polyfill, depending on your environment.
// Nothing else special needed.
'use strict';
var log = console.log.bind(console);
var Vehicle = {
init: function (options) {
var optionsDefaults = Object.assign({
make: '(make not supplied)',
model: '(model not supplied)'
}, options);
for (var arg in optionsDefaults) {
this[arg] = optionsDefaults[arg];
}
},
identify: function () {
return 'I am a very nice ' + this.make + ' ' + this.model;
}
};
var Car = Object.assign(Object.create(Vehicle), {
describe: function () {
log('Car: ' + this.identify());
}
});
var subaru = Object.create(Car);
subaru.init({ make: 'Subaru', model: 'Outback'});
var toyota = Object.create(Car);
toyota.init({ make: 'Toyota', model: 'Corolla' });
subaru.describe();
toyota.describe();
var Truck = Object.assign(Object.create(Vehicle), {
describe: function () {
log('Truck: ' + this.identify());
}
});
var dodge = Object.create(Truck);
dodge.init({ make: 'Dodge' });
var toyotaT = Object.create(Truck);
toyotaT.init({ make: 'Toyota', model: 'Tacoma' });
dodge.describe();
toyotaT.describe();
/* jshint esversion: 6, strict: global, devel: true */
// Requires Babel, which must also be set up correctly with the es2015 preset
// https://babeljs.io/docs/setup/#babel_cli
'use strict';
const log = console.log.bind(console);
// http://www.2ality.com/2015/01/es6-destructuring.html
// if called with zero arguments, the destructuring fails, because you can’t
// match an object pattern against undefined. That can be fixed via a default
// value. In the following code, the object pattern is matched against {} if
// there isn’t at least one argument.
let Vehicle = {
init({ make='(make not supplied)', model='(model not supplied)' } = {}) {
this.make = make;
this.model = model;
},
identify() {
return `I am a very nice ${ this.make } ${ this.model }`;
}
};
let Car = Object.create(Vehicle);
Car.describe = function () {
log(`Car: ${ this.identify() }`);
};
let subaru = Object.create(Car);
subaru.init({ make: 'Subaru', model: 'Outback'});
let toyota = Object.create(Car);
toyota.init({ make: 'Toyota', model: 'Corolla' });
subaru.describe();
toyota.describe();
let Truck = Object.create(Vehicle);
Truck.describe = function () {
log(`Truck: ${ this.identify() }`);
};
let dodge = Object.create(Truck);
dodge.init({ make: 'Dodge' });
let toyotaT = Object.create(Truck);
toyotaT.init({ make: 'Toyota', model: 'Tacoma' });
dodge.describe();
toyotaT.describe();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment