Skip to content

Instantly share code, notes, and snippets.

@geek
Last active November 5, 2016 21:57
Show Gist options
  • Save geek/79a91abd375f7aa4295895133b4ccfab to your computer and use it in GitHub Desktop.
Save geek/79a91abd375f7aa4295895133b4ccfab to your computer and use it in GitHub Desktop.
Demonstrating Mule inheritance in JavaScript
'use strict';
function Mule (obj, ...args) {
const mule = new Proxy({}, {
get: function (target, prop, receiver) {
const topKeys = Object.keys(target);
if (topKeys.includes(prop)) {
return target[prop];
}
if (!obj.mule) {
return undefined;
}
const muleKeys = Object.keys(obj.mule);
if (muleKeys.includes(prop)) {
return obj.mule[prop];
}
return undefined;
}
});
obj.apply(mule, args);
return mule;
};
Mule.inherits = function (child, parent) {
child.mule = Object.assign({}, parent.mule);
};
const Hello = function () {
this.hello = function () {
console.log('hello ');
};
};
Hello.mule = {};
Hello.mule.world = function () {
console.log('world');
};
const Foo = function (...args) {
Hello.apply(this, args);
}
Mule.inherits(Foo, Hello);
Foo.mule.bar = function () {
console.log('bar');
};
const hello = Mule(Hello);
hello.hello();
hello.world();
console.log(hello.bar);
const foo = Mule(Foo);
foo.hello();
foo.world();
foo.bar();
// Output
/*
hello
world
undefined
hello
world
bar
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment